求调 P2341 受欢迎的牛 G
查看原帖
求调 P2341 受欢迎的牛 G
932505
_LTC_Augenstern_楼主2024/4/22 22:45
#include <bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
using namespace std;
typedef long long ll;
int n, m, x, y, tmstmp, scc, zero, ans, dfn[100010], low[100010], color[100010], sz[100010], degree[100010];
vector<int> mp[100010];
stack<int> st;
bool alive[100010];
void tarjan(int u)
{
	dfn[u] = low[u] = ++ tmstmp;
	st.push(u), alive[u] = true;
	for(auto v : mp[u])
	{
		if(!dfn[v]) tarjan(v), low[u] = min(low[u], low[v]);
		else if(alive[v]) low[u] = min(low[u], dfn[v]);
	}
	if(dfn[u] == low[u])
	{
		int z;
		++ scc;
		do
		{
			z = st.top();
			st.pop();
			alive[z] = false;
			color[z] = scc;
			sz[scc] ++;
			st.pop();
		}while(z != u);
	}
	return;
}
int main()
{
	IOS;
	cin >> n >> m;
	for(int i = 0; i < m; i ++)
	{
		cin >> x >> y;
		mp[x].push_back(y);
	}
	for(int i = 1; i <= n; i ++) if(!dfn[i]) tarjan(i);
	for(int i = 1; i <= n; i ++) for(auto j : mp[i]) if(color[i] != color[j]) degree[color[i]] ++;
	for(int i = 1; i <= scc; i ++)
	{
		if(!degree[i]) 
		{
			zero ++;
			ans += sz[i];
			if(zero > 1)
			{
				cout << 0;
				return 0;
			}
		}
	}
	cout << ans;
	return 0;
}
2024/4/22 22:45
加载中...