秘密沉睡在森林里

Description

夏夜,早苗和诹访子在月光下玩起了挑竹签这一经典的游戏。

挑竹签,就是在桌上摆上一把竹签,每次从最上层挑走一根竹签。如果动了其他的竹签,就要换对手来挑。在所有的竹签都被挑走之后,谁挑走的竹签总数多,谁就胜了。

身为神明的诹访子自然会让早苗先手。为了获胜,早苗现在的问题是在诹访子出手之前最多能挑走多少竹签呢?

为了简化问题,我们假设当且仅当挑最上层的竹签不会动到其他竹签。

Analysis

题意:请打一个拓扑排序标程。

Code

#include <bits/stdc++.h>
int cnt[1000010],tot,head[1000010];
struct edge{
	int v,next;
}p[1000010];
void add(int u,int v){
	p[++tot].v=v;
	p[tot].next=head[u];
	head[u]=tot;
}
std::queue <int> b;
int main(){
	freopen("mikado.in","r",stdin);
	freopen("mikado.out","w",stdout);
	int n,m;
	scanf("%d%d",&n,&m);
	while(m--){
		int u,v;
		scanf("%d%d",&u,&v);
		add(u,v);
		cnt[v]++;
	}
	for(int i=1;i<=n;i++)
		if(!cnt[i])b.push(i);
	int ans=0;
	while(!b.empty()){
		int f=b.front();
		ans++;
		b.pop();
		for(int i=head[f];i;i=p[i].next){
			int v=p[i].v;
			cnt[v]--;
			if(!cnt[v])b.push(v);
		}
	}
	printf("%d
",ans);
	return 0;
}

原文地址:https://www.cnblogs.com/qswx/p/9644080.html