hdoj 2647 Reward【反向拓扑排序+分层】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sdz20172133/article/details/87895720

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
 

题意:

n个人,m条边,每条边a,b ,表示a比b的工资要多,每个人的工资至少888,问满足关系的工资总和至少多少?如果出现关系矛盾,输出-1

分析:

如果有环,可能是不存在的。

接下来,你就要对它分层了,因为上面的红字,所以我们反向建立拓扑排序,只有在更新时候它的度数被减为0 的时候,它才能被更新过来,相当于他是他的下一层,画画图就明白了,具体看代码把

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int N=10005;
vector<int> G[N];
int in[N],val[N];
//vector<int>path;

int n;
int cnt;
int topo()
{
    queue<int> Q;
    for(int i=1;i<=n;i++)
	{
		if(in[i]==0)
	     {
	     	Q.push(i);
	     	
	     }
	}
	while(!Q.empty())
	{
	    int y=Q.front();
		Q.pop();
		//path.push_back(y);
		cnt++;
	    for(int i=0;i<G[y].size();i++)
		{
		     in[G[y][i]]--;
		     if(in[G[y][i]]==0)
			 {
			 	//cout<<G[y][i]<<endl;
			 	Q.push(G[y][i]);
			 	val[G[y][i]]=val[y]+1;
			 }	
		}
	}
	  	
    
}
int main()
{
    int m;
    while(scanf("%d%d",&n,&m)!=-1)
    {
    	memset(in,0,sizeof(in));
    	memset(val,0,sizeof(val));
    	for(int i=0;i<=n;i++)
    		G[i].clear();
    		cnt=0;
    		//path.clear();
    		
        while(m--)
        {
        	int a,b;
            scanf("%d%d",&a,&b);
            G[b].push_back(a);
            in[a]++;
        }
        topo();
        if(cnt!=n)
        	printf("-1\n");
		else
		{     
		    long long ans=0;
			for(int i=1;i<=n;i++)
				ans+=(888+val[i]);
			printf("%lld\n",ans);
		}
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/87895720