嘟嘟嘟
水題一道,某谷又惡意評分。
合併沒有非是將兩棵樹的直徑的中點連一塊,記原來兩棵樹的直徑爲\(d_1, d_2\),那麼新的樹的直徑就是\(max(d_1, d_2, \lceil \frac{d_1}{2} \rceil + \lceil \frac{d_2}{2} \rceil + 1)\),用並查集合並,更新便可。ios
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<cctype> #include<vector> #include<stack> #include<queue> #include<assert.h> using namespace std; #define enter puts("") #define space putchar(' ') #define Mem(a, x) memset(a, x, sizeof(a)) #define In inline typedef long long ll; typedef double db; const int INF = 0x3f3f3f3f; const db eps = 1e-8; const int maxn = 3e5 + 5; In ll read() { ll ans = 0; char ch = getchar(), last = ' '; while(!isdigit(ch)) last = ch, ch = getchar(); while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); if(last == '-') ans = -ans; return ans; } In void write(ll x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar(x % 10 + '0'); } In void MYFILE() { #ifndef mrclr freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif } int n, m, Q; struct Edge { int nxt, to; }e[maxn << 1]; int head[maxn], ecnt = -1; In void addEdge(int x, int y) { e[++ecnt] = (Edge){head[x], y}; head[x] = ecnt; } int p[maxn]; In int Find(int x) {return x == p[x] ? x : p[x] = Find(p[x]);} int Max[maxn], dia[maxn]; In void dfs(int now, int _f, int id) { p[now] = id; int Max1 = 0, Max2 = 0; for(int i = head[now], v; ~i; i = e[i].nxt) { if((v = e[i].to) == _f) continue; dfs(v, now, id); if(Max[v] + 1 > Max1) Max2 = Max1, Max1 = Max[v] + 1; else if(Max[v] + 1 > Max2) Max2 = Max[v] + 1; } Max[now] = Max1; dia[id] = max(dia[id], Max1 + Max2); } int main() { //MYFILE(); Mem(head, -1); n = read(), m = read(), Q = read(); for(int i = 1; i <= m; ++i) { int x = read(), y = read(); addEdge(x, y), addEdge(y, x); } for(int i = 1; i <= n; ++i) if(!p[i]) dfs(i, 0, i); for(int i = 1; i <= Q; ++i) { int op = read(), x = read(); if(op == 1) write(dia[Find(x)]), enter; else { int y = read(); int px = Find(x), py = Find(y); if(px == py) continue; p[px] = py; dia[py] = max(max(dia[px], dia[py]), (dia[px] + 1) / 2 + (dia[py] + 1) / 2 + 1); } } return 0; }