HDU-2647 拓扑排序

版权声明:本文为博主原创文章,若需要引用、转载,只需注明来源及原文链接,若有错误,欢迎纠正。 https://blog.csdn.net/u014137295/article/details/87884424

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的为0,下一个为上一个+1;
代码:

#include<bits/stdc++.h>
#define maxn 10002
using namespace std;
inline int read(){
    int x=0,f=0;char ch=getchar();
    while(ch>'9'||ch<'0')f|=ch=='-',ch=getchar();
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return f?-x:x;
}
int n,m,in[maxn],ans[maxn];
vector<int>e[maxn];
void topo(){
	queue<int>q;
	for(int i=1;i<=n;++i)if(in[i]==0)q.push(i);
	int t=0,sum=0;
	while(!q.empty()){
		int now=q.front();q.pop();
		++t;
		for(int i=0;i<e[now].size();++i)if(--in[e[now][i]]==0)
			q.push(e[now][i]),ans[e[now][i]]=ans[now]+1;
	}
	if(t==n){
		for(int i=1;i<=n;++i)sum+=ans[i]+888;
		printf("%d\n",sum);
	}
	else puts("-1");
}
int main(){
	while(~scanf("%d%d",&n,&m)){
		for(int i=1;i<=n;++i)in[i]=ans[i]=0,e[i].clear();
		while(m--){
			int u=read(),v=read();
			e[v].push_back(u);
			++in[u];
		}
		topo();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u014137295/article/details/87884424
今日推荐