【杭电】[2647]Reward

Reward

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
 

给出某个工人的工资应该比另一个人高

问最低一共应该发多少工资

拓扑排序问题

若把工资最低的那些人标记为入度为0

第二低的标记为1

则每个人的工资应该为888+入度

运用了队列和邻接表优化


#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n;
int sum[10200];
int cnt[10200];
int head[10200];
struct node {
	int next;
	int to;
} a[20200];
int res;
int toposort() {
	res=0;
	queue<int>q;
	memset(sum,0,sizeof(sum));
	for(int i=1; i<=n; i++) {
		if(cnt[i]==0) {
			q.push(i);
			sum[i]=888;
		}
	}
	int t=0;
	while(!q.empty()) {
		int top=q.front();
		q.pop();
		t++;
		res+=sum[top];
		for(int i=head[top]; i!=-1; i=a[i].next) {
			if(--cnt[a[i].to]==0) {
				q.push(a[i].to);
				sum[a[i].to]=sum[top]+1;
			}
		}
	}
	return t<n?-1:res;
}
int main() {
	int m;
	while(scanf("%d %d",&n,&m)!=EOF) {
		memset(cnt,0,sizeof(cnt));
		memset(head,-1,sizeof(head));
		for(int i=0; i<m; i++) {
			int u,v;
			scanf("%d %d",&u,&v);
			a[i].to=u;
			a[i].next=head[v];
			head[v]=i;
			cnt[u]++;
		}
		printf("%d\n",toposort());
	}
	return 0;
}

题目地址:【杭电】[2647]Reward

posted @ 2016-08-06 09:59  BoilTask  阅读(13)  评论(0编辑  收藏  举报