Tarjan 全Wa 疑惑...
查看原帖
Tarjan 全Wa 疑惑...
188970
Twiter_ln楼主2023/11/11 09:58

求调

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>

using namespace std;
const int N = 10017;

int n, m, x, y;
int cb[N][N];

struct pot{
	int v, nxt;
}E[20*N];
int head[N], tot = 1;
inline void Add_edge(int u, int v) {
	E[++tot].v = v;
	E[tot].nxt = head[u];
	head[u] = tot;
}

int dfn[N], low[N], num;
int vis[N], stack[N], top;
int c[N], cnt;
vector <int> scc[N];
inline void tarj(int u) {
	dfn[u] = low[u] = ++ num;
	stack[++ top] = u;
	vis[u] = 1;
	
	int v;
	for(int i=head[u];i;i=E[i].nxt) {
		v = E[i].v;
		if(!dfn[v]) {
			tarj(v);
			low[u] = min(low[u], low[v]);
		} else if(vis[v]) low[u] = min(low[u], dfn[v]);
	}
	if(dfn[u] == low[u]) {
		++ cnt;
		do {
			v = stack[top --];
			vis[v] = 0;
			scc[cnt].push_back(v);
			c[v] = cnt;
		} while(u != v);
	}
}

int main() {
	
	scanf("%d%d", &n, &m);
	for(int i=1;i<=m;++i) {
		scanf("%d%d", &x, &y);
		if(cb[x][y] || x==y) continue;
		cb[x][y] = 1;
		
		Add_edge(x, y);
	}
	
	for(int i=1;i<=n;++i) {
		if(!dfn[i]) tarj(i);
	}
	
	for(int i=1;i<=cnt;++i) sort(scc[i].begin(), scc[i].end());
	
	bool b[N];
	int tag;
	printf("%d\n", cnt);
	for(int i=1;i<=n;++i) {
		if(b[c[i]]) continue;
		b[c[i]] = 1;
		for(int j=0;j<scc[c[i]].size();++j) printf("%d ", scc[c[i]][j]);
		putchar('\n');
	}
	
	return 0;
}
/*

6 8
1 2
1 5
2 6
5 6
6 1
5 3
6 4
3 4

3
1 2 5 6
3
4

*/
2023/11/11 09:58
加载中...