题目链接
题意:
给一个n个节点n条无向边的无向图,需要找出图中存在多少条长度大于1的路径。
思路:
因为边数大于1,只比树的边数多一条边,所以图中有且仅有一个环。很明显我们可以发现环上同一个子树的两点间有且仅有一条路径,不同子树间的两点存在两条路(环的两个方向),所以我们只需要找出环上的节点和它们分别的子节点数即可通过规律找出路径数。
ac代码:
#include <iostream>// 拓扑+dfs
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <bitset>
using namespace std;
#define int long long
const int maxn = 2e5 + 5;
int d[maxn];
int vis[maxn];
vector<int> q;
int ans = 0;
struct node {
int to, next;
};
int head[maxn];
node eg[maxn << 1];
int tot = 0;
int fans[maxn];
void add(int a,int b) {
eg[++tot] = { b,head[a] }; head[a] = tot;
eg[++tot] = { a,head[b] }; head[b] = tot;
return;
}
void dfs(int a, int fa) {
vis[a] = 0; ans++;
for (int i = head[a]; i; i = eg[i].next) {
if (vis[eg[i].to]) dfs(eg[i].to, a);
}
return;
}
queue<int>qq;
void topu() {
while (!qq.empty()) {
int tt = qq.front(); vis[tt] = 1; qq.pop();
for (int i = head[tt]; i; i = eg[i].next) {
d[eg[i].to]--;
if (d[eg[i].to] == 1) qq.push(eg[i].to);
}
}
return;
}
signed main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t; cin >> t;
while (t--) {
int n; cin >> n; tot = 0; q.clear();
for (int i = 1; i <= n; i++) d[i] = 0, vis[i] = 0, head[i] = 0, fans[i] = 0;
for (int i = 1; i <= n; i++) {
int a, b; cin >> a >> b;
add(a, b);
d[a]++, d[b]++;
}
//for (int i = 1; i <= n; i++) cout << d[i] << " "; cout << endl;
for (int i = 1; i <= n; i++) {
if (d[i] == 1) qq.push(i);
}
topu();
//for (int i = 1; i <= n; i++) cout << vis[i] << " "; cout << endl;
for (int i = 1; i <= n; i++) if (!vis[i]) q.push_back(i);
for (auto i : q) {
ans = 0;
dfs(i, -1);
fans[i] = ans;
}
//for (int i = 1; i <= n; i++) cout << fans[i] << " "; cout << endl;
int ffans = 0;
int sum = 0;
for (auto i : q) {
ffans += (1 + (fans[i] - 1)) * (fans[i] - 1) / 2;
if (!sum) sum = fans[i];
else {
ffans += sum * fans[i] * 2;
sum += fans[i];
}
}
cout << ffans << endl;
}
return 0;
}