Reward 【反向拓扑+队列实现】

来源:互联网 发布:大数据在小城市的应用 编辑:程序博客网 时间:2024/05/16 13:50

Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4767 Accepted Submission(s): 1456

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
大意 : 有m个要求 ,每个要求都是想着自己的 钱是比另一个人的多,
问 是否可以满足所有的要求,如果可以,就输出最少的花费,否则就输出-1
学习了
思路 : 如果正向a大于b的话,一开始的 总价值 无法确定,所以可以反向建图,这样就可以 拓扑 扫一遍, 就可以得出结果;

注意 , 这个图大,肯定是无法用 矩阵来存图,所以 可以使用 邻接表来存,另外 拓扑排序 是可以 用队列实现的 ;
代码

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<cmath>#include<queue>#include<stack>#include<map>#include<vector>#include<set>#define CLR(a,b) memset((a),(b),sizeof(a))#define inf 0x3f3f3f3f#define mod 100009#define LL long long#define M   200000#define ll o<<1#define rr o<<1|1#define lson o<<1,l,mid#define rson o<<1|1,mid+1,rusing namespace std;  //  邻接表 建图 省空间struct edge{    int to,next; } G[M]; int n,m;int head[M];int  in[M];int money[M];void getmap()  //  建造邻接表{    CLR(head,-1);    CLR(in,0);    int i,j;    for(i=0;i<m;i++) //反向建图    {        int a,b;        scanf("%d%d",&a,&b);        G[i].to=a;        G[i].next=head[b];        in[a]++;        head[b]=i;    }}void toposort(){    queue<int>Q;    int num=0;    int i,j;    int now,next;    for(i=1;i<=n;i++)    {        if(!in[i])         {            Q.push(i);            money[i]=888;        }    }    while(!Q.empty())    {        now=Q.front();Q.pop();        num++;        for(i=head[now];i!=-1;i=G[i].next)        {            --in[G[i].to];            if(in[G[i].to]==0)             {                money[G[i].to]=money[now]+1;                Q.push(G[i].to);            }        }    }    if(num!=n) printf("-1\n");    else     {        int sum=0;        for(i=1;i<=n;i++)        sum+=money[i];         printf("%d\n",sum);    }}int main(){    while(~scanf("%d%d",&n,&m))    {        getmap();        toposort();     }    return 0;}
0 1