codeforces 455C C. Civilization(树形dp+树的直径+并查集)
来源:互联网 发布:淘宝客是做什么的 编辑:程序博客网 时间:2024/05/18 19:38
题目链接:
codeforces 455C
题目大意:
给出一些点,他们之间初始存在一些边,给出两种操作,第一种是查询某个点所在的树的直径,另一种是将两个树合并,要求使合并后的树的直径最小。
题目分析:
- 首先算取没做操作前的连通块里的树的直径,也就是先dfs一遍,找到深度最大的点,然后从这个点再搜,找到的最远的距离就是这棵树的直径,因为可以证明从根搜深度最大的点一定是树的直径的一个端点,因为它可以通过到达次大的深度的点或者找到与它公共祖先不在根处的获得树的直径。
- 然后每次合并,我们可以知道得到的新的树的直径是
max{max{L1,L2},L1+12+L2+12+1} - 然后利用并查集记录连通块即可。
AC代码:
#include <iostream>#include <cstring>#include <cstdio>#include <vector>#include <algorithm>#define MAX 300007using namespace std;int n,m,q;vector<int> e[MAX];int fa[MAX];int ans[MAX];void clear(){ for ( int i = 0 ; i < MAX ; i++ ) e[i].clear(); for ( int i = 1 ; i < MAX ; i++ ) fa[i] = i;}void add ( int u , int v ){ e[u].push_back ( v ); e[v].push_back ( u );}int _find ( int x ){ return x == fa[x]?x:fa[x] = _find ( fa[x] );}void _union ( int x , int y , int f ){ x = _find ( x ); y = _find ( y ); if ( x > y ) swap ( x , y ); fa[y] = x; if ( f ) return; int xx = ans[x]; int yy = ans[y]; ans[x] = max ( max ( xx , yy ) , (xx+1)/2 + (yy+1)/2 +1 );}bool used[MAX];bool mark[MAX];int pp,dis;void dfs ( int u , int d , int p ){ if ( d > dis ) { dis = d; pp = u; } for ( int i = 0 ; i < e[u].size() ; i++ ) { int v = e[u][i]; if ( v == p ) continue; dfs ( v , d+1 , u ); }}int main ( ){ while ( ~scanf ( "%d%d%d" , &n , &m , &q) ) { clear(); int x,y,z; for ( int i = 0 ; i < m ; i++ ) { scanf ( "%d%d" , &x, &y); add ( x , y ); _union ( x , y , 1 ); } memset ( used , 0 , sizeof ( used ) ); for ( int i = 1 ; i <= n ; i++ ) { int x = _find ( i ); if ( used[x] ) continue; pp = dis = -1; used[x] = true; dfs ( x , 1 , -1 ); dis = 0; dfs ( pp , 0 , -1 ); ans[x] = dis; } for ( int i = 0 ; i < q ; i++ ) { scanf ( "%d" , &z ); if ( z == 1 ) { scanf ( "%d" , &x ); printf ( "%d\n" , ans[_find(x)] ); } else { scanf ( "%d%d" , &x , &y ); if ( _find(x) == _find(y) ) continue; _union ( x , y , 0 ); } } }}
0 0
- codeforces 455C C. Civilization(树形dp+树的直径+并查集)
- Codeforces 455C Civilization 树的直径+并查集
- 【树的直径+并查集】 codeforces 455C - Civilization
- Codeforces 455C Civilization(并查集+树形dp)
- CodeForces 455C Civilization(并查集+树直径)
- Codeforces 455C. Civilization (树的直径+并查集)
- 【打CF,学算法——四星级】CodeForces 455C Civilization (【详解】并查集+树的直径)
- Codeforces 455E Civilization【思维+树的直径+并查集】
- 【CodeForces】445C Civilization 并查集
- codeforces 455C Civilization 树的最长链+并查集
- Codeforces 455C Civilization(并查集+dfs)
- Codeforces 455C Civilization(并查集+dfs)
- codeforces round260 div1C&div2E Civilization 并查集+树的直径
- codeforces 466C Civilization 并查集+dfs
- Codeforces 455C —— Civilization(并查集,树上最长链)
- coderforces 455C 并查集+树的直径
- codeforces 455C Civilization
- CodeForces 455C-Civilization
- sjtu-acm-1033
- Permutation Sequence
- ZOJ 1221Risk_Floyd - Dijkstra
- unix高级编程
- GDataXMLNode应用
- codeforces 455C C. Civilization(树形dp+树的直径+并查集)
- 【设计模式】里氏代换
- 数据结构——概论
- 搭建tomcat服务器,目标可通过外网ip访问本机
- ORMLite框架(1)——入门用法
- hdu4135Co-prime
- Spring 别名的使用
- PAT 1033. To Fill or Not to Fill (25)
- 【C#】值类型VS引用类型and现金VS存折