tarjan 20pts求助
查看原帖
tarjan 20pts求助
527206
wjh2022楼主2023/5/3 14:35
//#pragma GCC optimize (2)
#include <bits/stdc++.h>
#define int long long
#define PII pair <int, int>

using namespace std;
const int N = 2e5 + 5;
const int M = 6e5 + 5;

int n, m;
int vis[N], low[N], dfn[N], head[N], scc_cnt[N];
int scc[N];
int cnt, ans, scc_count, num_count, point;
struct node {
	int nxt, u, v;
};
node a[M];
stack <int> s;
set <PII> dedup;

void add (int x, int y) {
	a[ ++ point].nxt = head[x];
	a[point].u = x;
	a[point].v = y;
	head[x] = point;
}

void tarjan (int u) {
	vis[u] = 1, low[u] = dfn[u] = ++ cnt;
	s.push (u);
	for (int i = head[u]; i; i = a[i].nxt) {
		int v = a[i].v;
		if (!dfn[v]) {
			tarjan (v);
			low[u] = min (low[u], low[v]);
		} else if (vis[v]) {
			low[u] = min (low[u], dfn[v]);
		}
	}
	
	if (low[u] == dfn[u]) {
		++ scc_count;
		while (!s.empty () && dfn[s.top ()] >= dfn[u]) {
			int k = s.top ();
			scc[k] = scc_count;
			s.pop ();
		}
	}
	vis[u] = 0;
}

signed main () {
	scanf ("%lld%lld", &n, &m);
	for (int i = 1; i <= m; i ++ ) {
		int u, v;
		scanf ("%lld%lld", &u, &v);
		PII pii_dedup(u, v);
		if (u == v || dedup.count (pii_dedup))	continue;
		add (u, v);
		dedup.insert (pii_dedup);
	}
	
	for (int i = 1; i <= n; i ++ )
		if (!dfn[i])
			tarjan (i);
	
	for (int i = 1; i <= n; i ++ ) {
		for (int j = head[i]; j; j = a[j].nxt) {
			if (scc[a[j].u] != scc[a[j].v])	scc_cnt[scc[a[j].u]] = 1;
		}
	}
	
	for (int i = 1; i <= scc_count; i ++ )
		printf ("%lld\n", scc_cnt[i]);
	printf ("%lld\n", ans);
	
	return 0;
}
2023/5/3 14:35
加载中...