传送门
题目描述
给你一个 n n n个点 n n n条边的无向图,问你图中一共有多少条简单路径
分析
很容易看出来这是一个基环树
在一个环内,每两个点都有两条路径可以到达,所以最后的答案为
n
∗
(
n
−
1
)
n * (n - 1)
n∗(n−1),然后我们去找环上每一个点构成的树,这棵树内的每两个点之间都只有一条简单路径,所以最后对答案的影响为
s
i
z
e
∗
(
s
i
z
e
−
1
)
/
2
size * (size - 1) / 2
size∗(size−1)/2
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10,M = 2 * N;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int h[N],ne[M],e[M],idx;
int n;
int pre[N];
bool st[N],in[N];
ll sum;
void add(int x,int y){
ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}
void dfs(int u,int fa){
st[u] = true;
pre[u] = fa;
for(int i = h[u];~i;i = ne[i]){
int j = e[i];
if(j == fa) continue;
if(st[j]){
if(in[j]) continue;
in[j] = true;
for(int k = u;k != j && k;k = pre[k]) in[k] = true;
}
else dfs(j,u);
}
}
void dfs1(int u,int fa){
sum++;
for(int i = h[u];~i;i = ne[i]){
int j = e[i];
if(j == fa || in[j]) continue;
dfs1(j,u);
}
}
int main() {
int T;
read(T);
while(T--){
read(n);
for(int i = 1;i <= n;i++) {
st[i] = in[i] = false;
h[i] = -1;
}
for(int i = 1;i <= n;i++) {
int a,b;
read(a),read(b);
add(a,b),add(b,a);
}
dfs(1,0);
ll res = (1ll * n - 1) * n;
for(int i = 1;i <= n;i++) if(in[i]) {
sum = 0;
dfs1(i,0);
res -= sum * (sum - 1) / 2;
}
dl(res);
}
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/