95求调
查看原帖
95求调
1028771
Retoayd楼主2025/1/22 12:32
#include <bits/stdc++.h>
#define int long long
#define Fast  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
using namespace std; 

const int N = 2e5 + 5, MOD = 1000000007;

int n, m, vis[N], ind[N], outd[N];
pair <int, int> a[N];
vector <int> g[N];

int dfn[N], low[N], instk[N], cnt[N], times, scc_cnt;
stack <int> stk;

void tarjan(int u) {
	dfn[u] = low[u] = ++times, instk[u] = 1;
	stk.push(u);
	for(auto & v : g[u]) {
		if(!dfn[v])
			tarjan(v), low[u] = min(low[u], low[v]);
		else if(instk[v])
			low[u] = min(low[u], dfn[v]);
	}
	if(dfn[u] == low[u]) {
		int v;
		scc_cnt++;
		do {
			v = stk.top();
			stk.pop();
			instk[v] = 0;
			cnt[scc_cnt]++;
		} while(v != u);
	}
}

void DFS(int u) {
	vis[u] = 1;
	for(auto & v : g[u]) 
		DFS(v);
}

signed main() {
	Fast;
	cin >> n >> m;
	for(int i = 1; i <= m; i++) {
		cin >> a[i].first >> a[i].second;
		auto it = find(g[a[i].first].begin(), g[a[i].first].end(), a[i].second);
		if(it != g[a[i].first].end())
			continue; 
		g[a[i].first].push_back(a[i].second);
		outd[a[i].first]++, ind[a[i].second]++;
	}
	for(int i = 1; i <= n; i++)
		if(!dfn[i])
			tarjan(i);
	for(int i = 1; i <= scc_cnt; i++)
		if(cnt[i] > 1)
			return cout << 0 << endl, 0;
	int sum = 0;
	for(int i = 1; i <= n; i++)
		if(!ind[i] && !outd[i])
			sum++;
	for(int i = 1; i <= n; i++)
		if(!vis[i] && outd[i] == 1 && !ind[i])
			DFS(i), sum++;
	int ans = 1;
	for(int i = 1; i <= sum; i++)
		ans = (ans * i) % MOD;
	cout << ans;
	return 0;
}
2025/1/22 12:32
加载中...