您的位置:首页 > 其它

HDOJ 2647 Reward (反向拓扑排序)

2015-08-18 09:17 253 查看

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 5773    Accepted Submission(s): 1763

[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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.
 

[align=left]Output[/align]
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.
 

[align=left]Sample Input[/align]

2 1
1 2
2 2
1 2
2 1

 

[align=left]Sample Output[/align]

1777
-1

注 - 此题为:   HDOJ 2647  Reward  (反向拓扑排序)

题意:   有n个人,他们提出m个要求(就是x的奖励要比y高)。问你能否满足所有人要求,若能输出最少花费的钱,反之 (即成环) 输出-1。

     由于数据较大,要用邻接表  反向建图。

已AC代码:

#include<cstdio>
#include<cstring>
#define MAX 21000
#include<queue>
using namespace std;

int n,m;
struct node{
int u,v,w;
int next;
}s[MAX];

int head[MAX];
int inde[MAX];

void topo()
{
queue<int>Q;
int i,j,top,ans,sum,rew[MAX];
for(i=1;i<=n;++i)
{
rew[i]=888; // 最小奖金
if(inde[i]==0) //寻找入度为 0 的
Q.push(i);
}
ans=sum=0;
while(!Q.empty())
{
top=Q.front();
Q.pop();
sum+=rew[top]; //总金额
inde[top]=-1; // 访问过
ans++;
for(i=head[top];i!=-1;i=s[i].next)
{
inde[s[i].v]--; // 查找与 top 相连的 inde 自减 1
if(inde[s[i].v]==0) //寻找入度为 0 的
{
Q.push(s[i].v);
}
rew[s[i].v]=rew[top]+1; // 与 top 相连的 奖金要 多于 top 的奖金
}
}
if(ans==n)
printf("%d\n",sum);
else
printf("-1\n");
}

int main()
{
int i,j,a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));
memset(inde,0,sizeof(inde));

for(i=0;i<m;++i) //反向建 临接表
{
scanf("%d%d",&a,&b);
s[i].u=b;
s[i].v=a;
s[i].next=head[b];
head[b]=i;
inde[a]++;
}
topo();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息