Codeforces 455C Civilization 樹的直徑+並查集

來源:互聯網
上載者:User

標籤:http   os   io   for   ar   amp   size   ad   

題目連結:點擊開啟連結

題意:

給定n個點 m條無向邊的圖 k個詢問
無重邊、自環、環
定義 2個點屬於一個國家:當這兩個點連通時
操作1 x:輸出x所在的國家內的最長路長度

操作2 x y:若x y屬於一個國家 則忽略
若不屬於一個國家,則在2個集合間連一條邊,使得連完後最長路最短

連2個集合的最長路一定是 找2個集合最長路的中點進行串連

則串連後的最長路長度為 path[x]/2 + path[y]/2 +1 (除2向上取整)


然後給每棵樹預先處理出樹的直徑就好了。

因為只需要找到樹的直徑的長度而不關心樹的直徑的路徑

所以bfs(x)的所有子樹,找其中最長的2個子樹長度相加就是直徑了。即bfs一次即可

#include <cstdio>#include <cstring>#include<iostream>#include <queue>#include <set>using namespace std;#define inf 10000000#define N 300005struct Edge{int to, nex;}edge[N<<1];int head[N], edgenum;void add(int u, int v){Edge E = {v, head[u]};edge[edgenum] = E;head[u] = edgenum++;}int f[N], path[N];int find(int x){return x==f[x]?x:f[x] = find(f[x]);}void Union(int x, int y){int fx = find(x), fy = find(y);if(fx == fy)return ;if(fx>fy)swap(fx, fy);f[fx] = fy;int now = path[fx]/2 + path[fy]/2 +1;if(path[fx]&1)now++;if(path[fy]&1)now++;path[fx] = path[fy] = max(max(path[fx], path[fy]), now);}int n, m;int dis[N];vector<int>G[N];int BFS(int x){ int E = x;queue<int>q;  for(int i = 0; i < G[f[x]].size(); i++)dis[G[f[x]][i]] = inf;q.push(x);dis[x]=0;while(!q.empty())  {  int u = q.front(); q.pop(); for(int i = head[u]; ~i ;i = edge[i].nex)  {  int v = edge[i].to; if(dis[v] > dis[u]+1){dis[v] = dis[u]+1;if(dis[v]>dis[E])E = v;q.push(v);}}}return E;  }void work(int x){int S = BFS(x);S = BFS(S);path[x] = dis[S];}set<int>s;void init(){s.clear();memset(head, -1, sizeof head); edgenum = 0;memset(path, 0, sizeof path);for(int i = 0; i <= n; i++)f[i] = i, G[i].clear();}int main(){  int i, u, v, q, op;while(cin>>n>>m>>q){init();while(m--){scanf("%d %d",&u,&v);add(u,v);add(v,u);Union(u,v);}for(i = 1; i <= n; i++)find(i);for(i = 1; i <= n; i++) {s.insert(f[i]);G[f[i]].push_back(i);}for(set<int>::iterator it = s.begin(); it!=s.end(); it++)work(*it);while(q--){scanf("%d %d",&op, &u);if(op==1){u = find(u);printf("%d\n", path[u]);}else {scanf("%d",&v);Union(u, v);}}}return 0;}  


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.