关闭

HDU 2647 Reward(拓扑排序)

211人阅读 评论(0) 收藏 举报
分类:

Reward

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


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的结点跳出结点集合,根据结点在哪一次跳出结点集合决定需要花费的钱,即888+top-1(第一个结点为888),根据跳出的结点数,来判断是否有环存在。

代码如下:

#include <stdio.h>
#include <vector>
#include <string.h>
#define MAX 10010
using namespace std;
int n,m;
int money[MAX];
int vis[MAX],indegree[MAX],f[MAX];
int sum=0,top,t;
vector <int>map[MAX];
void init()
{
	for(int i=1;i<MAX;i++)
		map[i].clear();		//清空邻接表 
	for(int i=0;i<MAX;i++)
		money[i]=888;		//初始工资 
	memset(indegree,0,sizeof(indegree)); 	//入度清零
	memset(f,0,sizeof(f));
	top=0;	//层数清零
	t=0;	//访问结点数清零 
}

void toposort()
{
	int i,j,k;
	bool p;
	p=true;
	while(p)
	{
		p=false;
		top++;
		for(i=1;i<=n;i++)
		{
			if(!indegree[i])
			{
				p=true;
				f[i]=top;
				money[i]=money[i]+top-1;
				t++;
			}
		}
		for(i=1;i<=n;i++)
		{
			if(f[i]==top)
			{
				for(k=0;k<map[i].size();k++)
				{
					int v=map[i][k];
					indegree[v]--;
				}
				indegree[i]=-1;
			}
		}
	}
	top--;
}

int main()
{
	int i,j;
	int a,b;
	while(~scanf("%d %d",&n,&m))
	{
		init();
		for(i=1;i<=m;i++)
		{
			scanf("%d %d",&a,&b);
			map[b].push_back(a);
			indegree[a]++;
		}
		toposort();		
		if(t==n)
		{
			int sum=0;
			for(i=1;i<=n;i++)
				sum+=money[i];
			printf("%d\n",sum);
		}
		else
			printf("-1\n");
	}
	
	return 0;
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:83162次
    • 积分:3079
    • 等级:
    • 排名:第11270名
    • 原创:226篇
    • 转载:28篇
    • 译文:0篇
    • 评论:21条
    博客专栏
    文章分类
    最新评论