posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          LCA 最近公共祖先問題 (2)

          Posted on 2007-07-14 13:24 ZelluX 閱讀(478) 評論(0)  編輯  收藏 所屬分類: Algorithm
          PKU1330,普通樹的LCA問題。把結點A的所有父結點都保存在一個hash數組中,然后從結點B開始向上搜索,直到發現hash數組中存在的元素為止。
          #include <stdio.h>
          #include 
          <stdlib.h>

          typedef 
          struct TreeNode *pTree;

          struct TreeNode
          {
              
          int value;
              pTree father;
          };

          main()
          {
              
          int cases, n, i;
              scanf(
          "%d"&cases);
              pTree nodes[
          10000];
              
          for (i = 0; i < 10000; i++)
              {
                  nodes[i] 
          = malloc(sizeof(struct TreeNode));
                  nodes[i]
          ->value = i;
              }
              
          int flag[10000];
              
          while (cases > 0)
              {
                  cases 
          --;
                  scanf(
          "%d"&n);
                  
          for (i = 0; i < n; i++)
                  {
                      nodes[i]
          ->father = NULL;
                  }
                  
          int x, y;
                  
          for (i = 0; i < n - 1; i++)
                  {
                      scanf(
          "%d %d"&x, &y);
                      nodes[y 
          - 1]->father = nodes[x - 1];
                  }
                  scanf(
          "%d %d"&x, &y);
                  
          for (i = 0; i < n - 1; i++)
                      flag[i] 
          = 0;
                  pTree p 
          = nodes[x - 1];
                  
          while (p != NULL)
                  {
                      flag[p
          ->value] = 1;
                      p 
          = p->father;
                  }
                  p 
          = nodes[y - 1];
                  
          while (p != NULL)
                  {
                      
          if (flag[p->value])
                      {
                          printf(
          "%d\n", p->value + 1);
                          
          break;
                      }
                      p 
          = p->father;
                  }
              }
              
          return 0;
          }


          主站蜘蛛池模板: 苍南县| 澎湖县| 昆山市| 宿州市| 长治县| 广安市| 大方县| 民丰县| 万源市| 丹凤县| 绵阳市| 当阳市| 曲沃县| 饶阳县| 共和县| 北海市| 临漳县| 莱芜市| 乌兰察布市| 衡东县| 清远市| 柳河县| 武穴市| 淮北市| 囊谦县| 出国| 措勤县| 泗阳县| 益阳市| 临夏市| 兴海县| 河北区| SHOW| 无锡市| 定陶县| 通化市| 崇明县| 南涧| 南开区| 延安市| 洪江市|