hdu 2647 拓扑排序 逆向建树

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个人 告诉你 两个序号a,b 表示a的奖励要大于b 
拓扑排序 逆向建树 那么每次到下一个入度为0的点是 奖励+1;
 
 
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e4+10;
int n,m;
vector<int> s[maxn];
int ind[maxn];
int vis[maxn];
int num[maxn];
void init(){
	memset(ind,0,sizeof(ind));
	memset(vis,0,sizeof(vis));
	memset(num,0,sizeof(num));
	for(int i=0;i<=n;i++)
		s[i].clear();
}

void toop(){
	queue<int> q;
	ll ans=0;
	int h=0;
	for(int i=1;i<=n;i++){
		if(ind[i]==0)  {
			q.push(i);
			vis[i]=1;
		}
	}
	while(!q.empty()){
		int u=q.front();
		q.pop();
		ans+=num[u]+888;
		h++;
		for(int i=0;i<s[u].size();i++){
			int v=s[u][i];
			ind[v]--;
			if(!vis[v] && ind[v]==0){
				q.push(v);
				num[v]=num[u]+1;
				vis[v]=1;
			}
		}
	}
	if(  h==n ) printf("%lld\n",ans);
	else puts("-1");
}

int main(){
	while(~scanf("%d%d",&n,&m)) {
		init();
		for(int i=0;i<m;i++){
			int a,b;
			scanf("%d%d",&a,&b);
			s[b].push_back(a);
			ind[a]++;
		}
		toop();
	}
	return 0;
}

  

 
 
 
 
posted @ 2019-08-17 15:04  杰瑞与汤姆  阅读(171)  评论(0编辑  收藏  举报