hdu2647——使用队列实现拓扑排序

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,m。n表示公司人数,m表示不同人之间的关系。a b表示a的工资大于b.

解决思路:只要小的放在上面,大的放在下面,反向建图就可以实现不同等级求值了。

代码:


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <cmath>
#include <stack>
#include <string>
#include <vector>
#include <map>
#define maxn 10005
using namespace std;
vector<int> vec[maxn];
int indegree[maxn];
struct Node
{
	int id,degree;//编号和层数 
}p,q;
queue<Node> Q;
int n,m;


void topSort()
{
	long long sum=0;//计算总工资 
	int cnt=0;//计算入队的人数 
	while(!Q.empty())
	{
		p=Q.front();
		Q.pop();
		cnt++;
		sum+=(888+p.degree);//层数越大的工资越高 
		int x=p.id;
		for(int i=0;i<vec[x].size();i++)//除去与x相连的边 
		{
			indegree[vec[x][i]]--;
			if(indegree[vec[x][i]]==0)//判断是否有入度为0的点 
			{
				q.id=vec[x][i];
				q.degree=p.degree+1;
				Q.push(q);//入队 
			}
		}
	}
	if(cnt==n)//如果人数刚好为n,则没有环 
		printf("%lld\n",sum);
	else
		printf("-1\n");
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		memset(indegree,0,sizeof(indegree));
		memset(vec,0,sizeof(vec));
		while(!Q.empty())
		{
			Q.pop();
		}
		int a,b;
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&a,&b);//题目中说的是a的工资大于b,所以要从b指向a,这样a就在下一层 
			vec[b].push_back(a);
			indegree[a]++;//入度++ 
		}
		for(int i=1;i<=n;i++)
		{
			if(!indegree[i])//寻找入度为0的点 
			{
				p.id=i,p.degree=0;
				Q.push(p);
			}
		}
		topSort();
	}
} 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值