您的位置:首页 > 其它

HDU 2647 Reward

2015-04-16 19:01 176 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2647

Reward

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4633 Accepted Submission(s): 1412



Problem Description
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


拓扑排序简单变形,如果你深知拓扑排序的原理,你很容易就知道应该在哪里改代码。此题加个数组记录每个顶点对应的值就OK了。

下面是AC代码:

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int maxn=10005;
vector<int>G[maxn];
int in[maxn],v[maxn],n,m,Count,sum;
void TopSort()
{
    Count=0;sum=0;
    queue<int>q;
    for(int i=1;i<=n;i++)
        if(in[i]==0) q.push(i);
    while(q.size())
    {
        int now=q.front();q.pop();
        Count++;sum+=v[now];
        for(int i=0;i<G[now].size();i++)
        {
            int next=G[now][i];
            in[next]--;
            if(in[next]==0)
            {
                q.push(next);
                v[next]=v[now]+1;
            }
        }
    }
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0;i<=n;i++) G[i].clear();
        fill(v,v+maxn,888);
        fill(in,in+maxn,0);
        while(m--)
        {
            int a,b;
            cin>>a>>b;
            G[b].push_back(a);
            in[a]++;
        }
        TopSort();
        if(Count<n) cout<<-1<<endl;
        else cout<<sum<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: