您的位置:首页 > 其它

HDU-2647-Reward(拓扑排序-逆向建图)

2018-02-28 10:57 381 查看
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

#include <bits/stdc++.h>
using namespace std;
#define maxn 100005
queue<int>q;
vector<int>t[maxn];
int ans,sum[maxn],in[maxn];
void init()
{
while(!q.empty())
q.pop();
for(int a = 0;a < maxn;a ++)
t[a].clear();
memset(in,0,sizeof(in));
ans=0;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
init();//初始化操作
int u,v;
for(int a = 0;a < m;a ++)//逆向建图
{
scanf("%d%d",&u,&v);
u--,v--;
in[u]++;
t[v].push_back(u);
}
for(int a = 0;a < n;a ++)
{
if(!in[a])//结点为0放入队列中,并初始化该节点的值为888
{
q.push(a);
sum[a]=888;
}
}
int cnt=0;
while(!q.empty())
{
cnt++;
int p = q.front();
q.pop();
for(int a = 0;a < t[p].size();a ++)//通过该节点找出比下一个结点(比该节点大)
{
in[t[p][a]]--;//对于找到的入度为零的点,要让其对应的弧头入度减1
if(in[t[p][a]]==0)//结点为0就入队
{
q.push(t[p][a]);
sum[t[p][a]]=sum[p]+1;//记录下应该发的工资
}
}
}
for(int a = 0;a < n;a ++)
ans=ans+sum[a];
if(cnt!=n)
ans=-1;
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: