Number of Simple Paths (拓扑找环+dfs)

题目链接
题意:
给一个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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值