hdu 2647 Reward

来源:互联网 发布:windows phone软件下载 编辑:程序博客网 时间:2024/06/05 02:57

click here ~~

                         RewardTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5763    Accepted Submission(s): 1756Problem DescriptionDandelion'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.InputOne 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.OutputFor 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 Input2 11 22 21 22 1Sample Output1777-1

题目大意:老板要给很多员工发奖金, 但是部分员工有个虚伪心态, 认为自己的奖金必须比某些人高才心理平衡; 但是老板很人道, 想满足所有人的要求, 并且很吝啬,想画的钱最少

输入若干个关系:
a b
a c
c b
意味着a 的工资必须比b的工资高 同时a 的工资比c高; c的工资比b高

当出现环的时候输出-1
解题思路:拓扑排序,注意初始化,上代码:

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <queue>using namespace std;const int maxn = 20010;int head[maxn], ip, indeg[maxn];int n, m, seq[maxn];struct note{    int v,next;} edge[maxn];void Init(){    memset(head, -1, sizeof(head));    memset(indeg, 0, sizeof(indeg));    ip = 0;}void addedge(int u, int v)//增加边{    edge[ip].v = v;    edge[ip].next = head[u];    head[u] = ip++;}int topo()//拓扑排序{    queue<int> q;    for(int i=1; i<=n; i++)        if(indeg[i] == 0)            q.push(i);    int k = 0;    bool res = false;    while(!q.empty())    {        if(q.size() != 1)            res = true;        int u = q.front();        q.pop();        k++;        for(int i=head[u]; i!=-1; i=edge[i].next)        {            int v = edge[i].v;            indeg[v]--;            if(indeg[v] == 0)            {                seq[v] = seq[u]+1;                q.push(v);            }        }    }    if(k < n) return -1;    if(res) return 0;    return 1;}int main(){    int u, v;    while(cin>>n>>m)    {        Init();        memset(seq, 0, sizeof(seq));//初始化        while(m--)        {            cin>>u>>v;            addedge(v,u);            indeg[u]++;        }        if(topo() >= 0)        {            int ans=0;            for(int i=1; i<=n; i++)                ans += seq[i];            ans += 888*n;            printf("%d\n",ans);        }        else            puts("-1");    }    return 0;}
0 0