离奇全WA案
查看原帖
离奇全WA案
1054952
zzCX_df楼主2025/7/27 19:14

about 样例全过

#include <bits/stdc++.h>
typedef long long ll;

using namespace std;

const int N = 1100000;
int n, st, num, tot, f[N], d[N], sz[N], cnt[N], son[N];
ll ans;
vector<int> edges[N];

inline void dfs(int p, int fa) {
    d[p] = d[fa] + 1;
    cnt[d[p]]++;
    sz[p] = 1;
    for (auto y : edges[p]) if (y != fa) {
        dfs(y, p);
        sz[p] += sz[y];
    }
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &f[i]);
        edges[f[i]].push_back(i);
        edges[i].push_back(f[i]);
        if (f[i] == i)
            st = i;
        if (f[i] == 1 && i != 1)
            son[++num] = i;
    }
    dfs(st, st);
    tot = sz[son[1]];
    for (int i = 2; i <= num; tot += sz[son[i]], i++) 
        ans += 2LL * tot * sz[son[i]];
    memset(cnt, 0, sizeof(cnt));
    for (int i = 1; i <= num; i++) {
        d[st] = 0;
        dfs(son[i], st);
        for (int j = 1; j <= n && cnt[j]; j++) {
            ans += 1LL * cnt[j] * (cnt[j] - 1);
            cnt[j] = 0;
        }
    }
    ans += 0LL + 3 * n - 2;
    printf("%lld\n", ans);
    return 0;
}
2025/7/27 19:14
加载中...