hdu2647 拓扑排序+分层

Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards. 
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.

Input

One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000) 
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.

Output

For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.

Sample Input

2 1
1 2
2 2
1 2
2 1

Sample Output

1777
-1
蒲公英的叔叔是工厂的老板。 随着春节的到来,他想向工人分发奖励。 现在他在如何分配奖励方面遇到了麻烦。
工人们会比较他们的奖励,而有些人可能会要求分配奖励,就像奖励应该超过b的那样.Dandelion的解决方案想要满足所有的要求,当然,他想用最少的钱。每件工作都是 奖励至少是888,因为这是一个幸运数字。
输入
一行有两个整数n和m,代表作品数量和需求数量。(n <= 10000,m <= 20000)
然后m行,每行包含两个整数a和b,代表一个奖励应该比b更多。
产量
对于每一个案例,打印最少钱蒲公英的叔叔需要分发。如果不可能满足所有作品的要求,打印-1

详解:https://blog.csdn.net/mengxiang000000/article/details/51303271

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
const int maxn=20000+10;
int n,m;
int d[maxn];
vector<int> G[maxn];
int in[maxn];
int topo()
{
    queue<int> Q;
    for(int i=1;i<=n;i++)
    if(!in[i])
    {
        Q.push(i);
        d[i]=1;
    }
    int sum=0;
    while(!Q.empty())
    {
        int u=Q.front(); Q.pop();
        sum++;
        for(int i=0;i<G[u].size();i++)
        {
            int v=G[u][i];
            d[v]=d[u]+1;
            if(--in[v]==0) Q.push(v);
        }
    }
   if(sum==n)return 1;
   else
   {
       return 0;
   }
}
int main()
{

    while(~scanf("%d%d",&n,&m))
    {
        memset(in,0,sizeof(in));


        memset(d,0,sizeof(d));
        for(int i=1;i<=n;i++)
        {
            G[i].clear();

        }
        for(int i=1;i<=m;i++)
        {
            int u,v;
            cin>>u>>v;
                G[v].push_back(u);
                in[u]++;
        }
        if(topo()==0)
        {
            cout<<"-1"<<endl;
        }
        else
        {
            int sum=0;
            for(int i=1;i<=n;i++)
            {
                sum+=(888+d[i]-1);
            }
            cout<<sum<<endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/87902346