标签:training oid mission first http sam osi optimize value
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3373 Accepted Submission(s): 1461
#pragma GCC optimize(2) #include <bits/stdc++.h> #define lowbit(x) x&(-x) typedef long long ll; using namespace std; const int maxn = 2e5 + 100000; ll n; ll siz[maxn], sum[maxn], cnt; ll color[maxn], vis[maxn]; struct node { int to, nx; } o[maxn << 1]; int head[maxn]; ll res; inline void add_edge(int u, int v) { o[++cnt] = (node) {v, head[u]}; head[u] = cnt; } inline void solve(int cur, int fa) { siz[cur] = 1; ll pre = sum[color[cur]]; ll e = 0; for (register int i = head[cur]; i; i = o[i].nx) { int to = o[i].to; if (to == fa)continue; solve(to, cur); siz[cur] += siz[to]; ll nx = sum[color[cur]] - pre; ll fur = nx; nx = siz[to] - nx; res -= nx * (nx - 1) / 2; pre = sum[color[cur]]; e += fur; } sum[color[cur]] += siz[cur] - e; } int Case; int main() { #ifndef ONLINE_JUDGE freopen("1.txt", "r", stdin); #endif while (scanf("%lld", &n) != EOF) { ll tot = 0; cnt = 0; memset(head, 0, sizeof(head)); memset(vis, 0, sizeof(vis)); memset(sum,0,sizeof(sum)); for (register int i = 1; i <= n; ++i) { scanf("%d", &color[i]); if (!vis[color[i]]) { ++tot; vis[color[i]] = 1; } } for (register int i = 1, u, v; i < n; ++i) { scanf("%d%d", &u, &v); add_edge(u, v); add_edge(v, u); } res = tot * n * (n - 1) / 2; solve(1, -1); for (register int i = 1; i <= n; ++i) { if (!sum[i])continue; ll leave = n - sum[i]; res -= leave * (leave - 1) / 2; } printf("Case #%d: ", ++Case); printf("%lld\n", res); } return 0; }
标签:training oid mission first http sam osi optimize value
原文地址:https://www.cnblogs.com/czy-power/p/11451657.html