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;
}
相关文章推荐
- 详解图的应用(最小生成树、拓扑排序、关键路径、最短路径)
- 初学图论-Kahn拓扑排序算法(Kahn's Topological Sort Algorithm)
- HDU 3342
- hdu 1285 确定比赛名次 (简单的拓扑排序)
- hdu 2049 产生冠军(拓扑排序)
- [BZOJ2330][SCOI2011][拓扑排序][强连通分量][Tarjan]Candy
- Course Schedule
- LeetCode Course Schedule II
- 【Leetcode】Course Schedule II #210
- poj1094 拓扑排序
- (转)拓扑排序
- [leetcode]Course Schedule
- poj_1094
- cf_290(div2)A,B,C
- 图论算法(1)--- 如何求每一个节点在DAG中的最大深度
- hdu 3342 拓扑排序
- hdu 2647 拓扑排序
- UVa 1572 拓扑排序 判断有向图是否有环
- UVa10305拓扑排序入门题 可做模板用
- Sorting It All Out(简单的拓扑排序)