Reward
Time Limit: 1000 ms / Memory Limit: 32768 kb
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
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>gra[10005];
queue<int>q;
int mon[10005];
int ver,edge;
int ans;
int least;
void topsort()
{
int cnt=0;
for(int i=1;i<=ver;++i)
{
if(gra[i][0]==0)
{
q.push(i);
}
}
while(!q.empty())
{
int u=q.front();
cnt++;
ans+=mon[u];
q.pop();
for(int i=1;i<gra[u].size();++i)
{
if(--gra[gra[u][i]][0]==0)
{
q.push(gra[u][i]);
mon[gra[u][i]]=mon[u]+1;
}
}
}
if(cnt!=ver)
{printf("-1\n");
return;}
else
{
printf("%d\n",ans);
return;
}
}
int main(void)
{
while(~scanf("%d%d",&ver,&edge))
{
ans=0;
for(int i=1;i<=ver;++i)
{
gra[i].clear();
mon[i]=888;
gra[i].push_back(0);
}
for(int i=1;i<=edge;++i)
{
int u,v;
scanf("%d%d",&u,&v);
gra[v].push_back(u);
gra[u][0]++;
}
topsort();
}
}