Author: lllyouo
Date: 20250422
tag: tarjan、割点
link: https://www.acwing.com/problem/content/365/问题描述
分析
略
参考代码
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 5e5 + 10;
int h[N], e[M * 2], ne[M * 2], idx;
int dfn[N], low[N], num;
bool cut[N];
long long ans[N], sz[N];
int n, m, root;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void tarjan(int x) {
dfn[x] = low[x] = ++num;
int child = 0;
sz[x] = 1;
long long sum = 0, sum_s = 0;
for (int i = h[x]; i != -1; i = ne[i]) {
int y = e[i];
if (!dfn[y]) {
tarjan(y);
sz[x] += sz[y];
low[x] = min(low[x], low[y]);
if (low[y] >= dfn[x]) {
child++;
if (x != root || child > 1) cut[x] = true;
sum += sz[y] * (n - sz[y]);
sum_s += sz[y];
}
} else low[x] = min(low[x], dfn[y]);
}
if (cut[x]) ans[x] = sum + (n - 1) + (n - 1 - sum_s) * (1 + sum_s);
else ans[x] = 2 * (n - 1);
}
int main() {
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++) {
int a, b; cin >> a >> b;
add(a, b), add(b, a);
}
tarjan(1);
for (int i = 1; i <= n; i++) cout << ans[i] << endl;
return 0;
}