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
原创粉丝点击