例4.15 奖金(拓扑排序)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string> 
#include<algorithm>
int n,m;
int f[10001];
int tree[10001][301];
int r[10001],ans=0;
using namespace std;
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        tree[b][++tree[b][0]]=a;//比 b 小的数 
        r[a]++;//入度 ,多少个数比他小 
    }
    for(int i=1;i<=n;i++)
     f[i]=100;

    int tot=0,k=0;
    while(tot<n)
    {
        int t=0;
        for(int i=1;i<=n;i++)
          if(r[i]==0){
            tot++;t++;ans+=100;
            f[tot]=i;
            r[i]=0xfffffff;
          }

        if(t==0) {     //找不到入度为0的点 , 构成环 
            printf("Poor Xed");
            return 0;
        }

        ans+=k*t;
        k++;

        for(int i=0;i<t;i++)
         for(int j=1;j<=tree[f[tot-i]][0];j++)
           r[tree[f[tot-i]][j]]--; //比入栈的数大的数的入度-1 
    }
    printf("%d",ans);
    return 0; 
}
原文地址:https://www.cnblogs.com/dfsac/p/6819769.html