Reward (拓扑排序)

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

他们的钱是分层的,倒过来排序就方便操作了

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<vector>
using namespace std;
vector<int>a[10005];
int qian[10005];
int vis[10005];
int b[10005];
int main()
{
	int n,m;
	while(~scanf("%d %d",&n,&m))
	{
		map<int ,map<int,int> >p;
		memset(vis,0,sizeof(vis));
		memset(b,0,sizeof(b));
		memset(qian,0,sizeof(qian));
		for(int i=0;i<m;i++)
		{
			int w,e;
			scanf("%d %d",&e,&w);//倒过来了
			if(p[w][e]==0)
			{
				a[w].push_back(e);
				vis[e]++;p[w][e]++;
			}
		}
		queue<int>que;
	    int u=1;int sum=0;int w=-1;
		while(true)
		{
			int ok=1;w++;
			for(int i=1;i<=n;i++)
		    {
			    if(vis[i]==0&&b[i]==0)
			    {
			    	b[i]=1;
			    	if(u==1)
//			    	u=0;
//			    	else
//			    	printf(" ");
//			    	printf("%d",i);
                    qian[i]=w;
                   
			    	sum++;
			    	ok=0;
			    	
					que.push(i);
			
				}	
			  
		    }
		    while(!que.empty())
		    {
		    	int w=que.front();que.pop();
		    	for(int j=0;j<a[w].size();j++)
				{
					   	vis[a[w][j]]--;  
				}
			}
		    if(ok==1)
		    {
		    	break;
			}
		}
		int ans=0;
		for(int i=1;i<=n;i++)
		ans+=qian[i];
		if(sum==n)
		printf("%d\n",888*n+ans);
		else
		printf("-1\n");
		for(int i=1;i<=n;i++)
		a[i].clear();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liuliu2333/article/details/81414267