WA on #4 求助
查看原帖
WA on #4 求助
675466
zzx0102楼主2023/1/17 13:58
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define I inline
#define Mt(a, b) memset(a, b, sizeof a)
#define W while
#define CI const int
#define gc getchar
namespace SlowI{
    I void Read(int &x) {
        x = 0; char ch = gc();
        W(ch < '0' || ch > '9') ch = gc();
        W(ch >= '0' && ch <= '9') x = x * 10 + (ch ^ 48), ch = gc();
    }
    I void Read(int &x, int &y) {Read(x), Read(y);}
} using namespace SlowI;
CI N = 200010; int n; int a[N], b[N], c[N];
int h[N], to[N * 2], nxt[N * 2], idx;
I void add(int a, int b) {
    to[idx] = b;
    nxt[idx] = h[a];
    h[a] = idx++;
}
int rt[N], d[N][2];
I void init() {for(int i = 1; i <= n; i++) rt[i] = i;}
I int find(int x) {return rt[x] == x ? x : rt[x] = find(rt[x]);}
I void merge(int a, int b) {rt[find(b)] = find(a);}
bool vis[N];
I int bfs(int s, int fl) {
    queue<int> q; Mt(vis, 0); q.push(s); d[s][fl] = 0; vis[s] = 1;
    W(!q.empty()) {
        int u = q.front(); q.pop();
        for(int i = h[u]; i != -1; i = nxt[i]) {
            int v = to[i]; if(vis[v]) continue;
            d[v][fl] = d[u][fl] + 1; vis[v] = 1;
            q.push(v);
        }
    }
    int ans = 0;
    for(int i = 1; i <= n; i++) if(find(i) == i && d[i][fl] > d[ans][fl]) ans = i;
    return ans;
}
signed main() {
    Read(n); for(int i = 1; i <= n; i++) Read(c[i]); init(); Mt(h, -1);
    for(int i = 1; i < n; i++) {
        Read(a[i], b[i]);
        if(c[a[i]] == c[b[i]]) merge(a[i], b[i]);
    }
    for(int i = 1; i < n; i++) if(find(a[i]) != find(b[i])) {
        add(rt[a[i]], rt[b[i]]); add(rt[b[i]], rt[a[i]]);
    }
    int s = bfs(1, 0); int t = bfs(s, 1);
    cout << (d[t][1] + 1) / 2 << endl;
    return 0;
}
/*
11
0 0 0 1 0 0 1 1 1 1 0
1 2
2 3
2 4
4 5
4 6
4 7
8 9
8 10
10 11
1 8

*/
2023/1/17 13:58
加载中...