HDOJ 2586 How far away? LCA

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   for   ar   div   

http://acm.hdu.edu.cn/showproblem.php?pid=2586

題意:

給一棵樹,多次查詢點到點距離。

分析:

d[x][y] = d[x][root] + d[y][root] - 2 * d[lca(x,y)][root],所以求lca即可。因為tarjan是在dfs的過程中求lca,順便就把點到根的距離也求了。

敲了代碼才發現,講解的虛擬碼都是先遞迴子節點,染色,再回答詢問的順序,但是平時寫的時候一般是建了雙向邊,先遞迴子節點再染色會導致環的情況從而死迴圈。所以網上的題解大多是先染色,再查詢,再遞迴子節點。不過我試了一下,至少這一題,先染色,然後先回答詢問或是先遞迴子節點都是可以AC的。

 1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 using namespace std; 6  7 typedef pair<int, int> P; 8 const int maxn = 40100; 9 10 int T, n, m, x, y, z;11 int f[maxn], d[maxn], ans[300];12 bool vis[maxn];13 vector<P> e[maxn], q[maxn];14 15 int getf(int x)16 {17     if (f[x] == x) return x;18     return f[x] = getf(f[x]);19 }20 void unionxy(int x, int y)21 {22     int xroot = getf(x), yroot = getf(y);23     f[yroot] = xroot;24 }25 void tarjan(int x)26 {27     f[x] = x;28     vis[x] = true;29     for (int i = 0; i < q[x].size(); i++){30         int v = q[x][i].first, id = q[x][i].second;31         if (vis[v]){32             int lca = f[getf(v)];33             ans[id] = d[x] + d[v] - 2 * d[lca];34         }35     }36     for (int i = 0; i < e[x].size(); i++){37         int v = e[x][i].first, w = e[x][i].second;38         if (!vis[v]){39             d[v] = d[x] + w;40             tarjan(v);41             unionxy(x, v);42             f[getf(x)] = x;43         }44     }45 }46 int main()47 {48     scanf("%d", &T);49     while(T--)50     {51         scanf("%d %d", &n, &m);52         for (int i = 0; i <= n; i++){53             q[i].clear(); e[i].clear();54         }55         for (int i = 1; i < n; i++){56             scanf("%d%d%d", &x, &y, &z);57             e[x].push_back(make_pair(y, z));58             e[y].push_back(make_pair(x, z));59         }60         for (int i = 0; i < m; i++){61             scanf("%d %d", &x, &y);62             if (x == y) ans[i] = 0;63             else{64                 q[x].push_back(make_pair(y, i));65                 q[y].push_back(make_pair(x, i));66             }67         }68         memset(vis, 0, sizeof(vis));69         d[1] = 0;70         tarjan(1);71         for (int i = 0; i < m; i++)72             printf("%d\n", ans[i]);73     }74     return 0;75 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.