码迷,mamicode.com
首页 > 其他好文 > 详细

Codeforces 455C Civilization 树的直径+并查集

时间:2014-08-09 13:29:37      阅读:350      评论:0      收藏:0      [点我收藏+]

标签: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 300005
struct 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;
}  


Codeforces 455C Civilization 树的直径+并查集,布布扣,bubuko.com

Codeforces 455C Civilization 树的直径+并查集

标签:http   os   io   for   ar   amp   size   ad   

原文地址:http://blog.csdn.net/qq574857122/article/details/38455437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!