Description
挑竹签——小时候的游戏
夏夜,早苗和诹访子在月光下玩起了挑竹签这一经典的游戏。
挑竹签,就是在桌上摆上一把竹签,每次从最上层挑走一根竹签。如果动了其他的竹签,就要换对手来挑。在所有的竹签都被挑走之后,谁挑走的竹签总数多,谁就胜了。
身为神明的诹访子自然会让早苗先手。为了获胜,早苗现在的问题是,在诹访子出手之前最多能挑走多少竹签呢?
为了简化问题,我们假设当且仅当挑最上层的竹签不会动到其他竹签。
夏夜,早苗和诹访子在月光下玩起了挑竹签这一经典的游戏。
挑竹签,就是在桌上摆上一把竹签,每次从最上层挑走一根竹签。如果动了其他的竹签,就要换对手来挑。在所有的竹签都被挑走之后,谁挑走的竹签总数多,谁就胜了。
身为神明的诹访子自然会让早苗先手。为了获胜,早苗现在的问题是,在诹访子出手之前最多能挑走多少竹签呢?
为了简化问题,我们假设当且仅当挑最上层的竹签不会动到其他竹签。
Input
输入文件mikado.in。
第一行输入两个整数n,m, 表示竹签的根数和竹签之间相压关系数。
第二行到m+1 行每行两个整数u,v,表示第u 根竹签压住了第v 根竹签。
第一行输入两个整数n,m, 表示竹签的根数和竹签之间相压关系数。
第二行到m+1 行每行两个整数u,v,表示第u 根竹签压住了第v 根竹签。
Output
输出文件mikado.out。
一共一行,一个整数sum,表示最多能拿走sum 根竹签。
一共一行,一个整数sum,表示最多能拿走sum 根竹签。
Sample Input
6 6
1 2
2 3
3 1
4 3
4 5
6 5
Sample Output
3
样例解释:
一共有6 根竹签,其中1 压住2,2 压住3,3 压住1,4 压住3 和5,6 压住5。最优方案中,我们可以依次挑走4、6、5 三根竹签。而剩下的三根相互压住,都无法挑走。所以最多能挑走3 根竹签。
Data Constraint
对于20% 的数据,有1<= n,m<= 20。
对于40% 的数据,有1 <= n,m <= 1 000。
对于100% 的数据,有1 <= n,m <= 1 000 000。
对于40% 的数据,有1 <= n,m <= 1 000。
对于100% 的数据,有1 <= n,m <= 1 000 000。
题解
- 其实这题可以转换为求出有多少个点不在环内
- 容易想到拓扑排序
- 拓扑排序的做法:
- 每次加入没有入度的点,在将与它相连的边删去
- 那么能被删去的点,其实就是不在环内的点
代码
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 using namespace std; 7 struct edge{ int to,from; }e[1000010]; 8 int n,m,head,tail,ans,k[1000010],d[1000010],cnt,last[1000010]; 9 void insert(int x,int y) { d[y]++; e[++cnt].to=y; e[cnt].from=last[x]; last[x]=cnt; } 10 int main() 11 { 12 freopen("mikado.in","r",stdin); 13 freopen("mikado.out","w",stdout); 14 scanf("%d%d",&n,&m); 15 for (int i=1;i<=m;i++) 16 { 17 int x,y; 18 scanf("%d%d",&x,&y); 19 insert(x,y); 20 } 21 head=1; tail=0; 22 for (int i=1;i<=n;i++) 23 if (d[i]==0) 24 k[++tail]=i; 25 while (head<=tail) 26 { 27 int u=k[head]; head++; 28 ans++; 29 for (int i=last[u];i;i=e[i].from) 30 { 31 d[e[i].to]--; 32 if (d[e[i].to]==0) k[++tail]=e[i].to; 33 } 34 } 35 printf("%d",ans); 36 return 0; 37 }