跳到正文

个人记录

a

cje130725约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年3月30日
收录
2026年7月14日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10, M = 5e5 + 10;
struct Node {
	int to, next;
} a[M];
int pre[N], k = 0;

int dfn[N], low[N], times = 0,dout[N],din[N];
stack<int> st;
bool inst[N];
int cnt = 0;
int si[N];
int id[N];

int n, m, x, y;

void tarjan(int x) {
	dfn[x] = low[x] = ++times;
	st.push(x);
	inst[x] = true;
	for (int i = pre[x]; i; i = a[i].next) {
		int to = a[i].to;
		if (!dfn[to]) {
			tarjan(to);
			low[x] = min(low[x], low[to]);
		} else if (inst[to]) low[x] = min(low[x], dfn[to]);
	}
	if (low[x] == dfn[x]) {
		cnt++;
		int t;
		do {
			t = st.top();
			st.pop();
			inst[t] = false;
			si[cnt]++;
			id[t] = cnt;
		} while (t != x);
	}
}

void add(int u, int v) {
	a[++k] = {v, pre[u]};
	pre[u] = k;
}

int IN[N];

int main() {
//	freopen("001.in","r",stdin);
//	freopen("001.out","w",stdout);
	//srand((unsigned int)time(NULL));
	cin>>n>>m;
	for (int i = 1; i <= m; i++) {
		cin>>x>>y;
		add(x, y);
		IN[y]++;
	}
	int cc=0,ans1=0,ans2=0;
	for(int i=1;i<=n;i++){
		if(IN[i]==0){
			ans2++;
		}
	}
	for (int i = 1; i <= n; i++) {
		if (!dfn[i]) {
			tarjan(i);
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=pre[i];j;j=a[j].next){
			int to=a[j].to;
			int x=id[i],y=id[to];
			if(x!=y){
				dout[x]++;
                din[y]++;
			}
		}
	}
	for(int i=1;i<=cnt;i++){
		if(dout[i]==0){
			cc++;
			ans1=si[i];
			if(cc>1){
                ans1=0;
				break;
			}
		}
	}
    cc=0;
    cout<<ans1<<' '<<n-ans2;
	return 0;
}
原文