HDU 2647 Reward (拓扑排序)

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11792    Accepted Submission(s): 3789


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 11 22 21 22 1
 

Sample Output
 
  
1777-1


题意:老板要给n个员工发年终奖金,然后给出m个需求 (a,b),表示a的奖金要比b的多,然后呢,老板决定每个员工至少可以拿888元,现在老板总共至少需要发多少奖金。如果满足不了就输出-1

 

思路:

利用vector,直接用数组会超内容(也可以用邻接表),与上题相似。但是需要反向存储,将获得最少钱的当拓扑排序的起始点。然后将可以获得相同的钱的人记录下来。最后先判断是否成立,不能成环(A->B->C->A),然后计算最终的钱。



#include<bits/stdc++.h>

using namespace std;
int n,m;
vector<int>maps[10010];
int in[10010],dept[10010],dd[10010];

int main(){
	int x,y;
	while(~scanf("%d%d",&n,&m)){
		int cnt1=0;
		for(int i=1;i<=n;i++) maps[i].clear();
		memset(in,0,sizeof in);
		memset(dept,0,sizeof dept);
		memset(dd,0,sizeof dd);
		for(int i=1;i<=m;i++){
			scanf("%d%d",&x,&y);
			maps[y].push_back(x);
			in[x]++;
		}
		while(1){
			int cnt=0;
			for(int i=1;i<=n;i++){
				if(in[i]==0){
					in[i]=-1;
					//将入度为0的,全部记录下来。(方便后面算钱)
					dept[cnt++]=i;
				}
			}
			if(cnt==0) break;
//每种奖金数的个数。(888元的个数,889元的个数…..)
			dd[cnt1++]=cnt;
			//减去数每个点的,所连接的另一个点的入度
			for(int j=0;j<cnt;j++){
				for(int i=0;i<maps[dept[j]].size();i++){
					if(maps[dept[j]][i]!=0){
						in[maps[dept[j]][i]]--;
						maps[dept[j]][i]=0;
					}
				}
			}
		}
		int f=0,sum=0,x=888;
		for(int i=1;i<=n;i++){
			if(in[i]!=-1){
				f=1;
				break;
			}
		}
		for(int i=0;i<cnt1;i++){
			sum+=dd[i]*x;
			x++;
		}
		if(!f) printf("%d\n",sum);
		else printf("-1\n");
	}
}

猜你喜欢

转载自blog.csdn.net/rvelamen/article/details/80621378