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
Author
dandelion
Source
曾是惊鸿照影来
Recommend
yifenfei
利用topo排序写
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int m,n;
int in[20000];
vector<int>edge[20000];
/*struct node
{
int from,to;
}data[200002];*/
int topo()
{
int ans=0;
queue<pair<int ,int > >q;//first表示点,second表示等级
for(int i=1;i<=m;i++)
{
if(in[i]==0)
{
q.push(make_pair(i,0));//等级从0开始
in[i]=-1;//标记该点表示该点以取出
}
}
while(!q.empty())
{
int pos=q.front().first;
int base=q.front().second;
ans += 888 + base;
q.pop();
for(int i=0;i<edge[pos].size();i++)
{
int ne=edge[pos][i];
in[ne]--;
if(in[ne]==0)
{
q.push(make_pair(ne,base+1));
in[ne]=-1;
}
}
}
for(int i=1;i<=m;i++)
{
if(in[i] != -1)
return -1;
}
return ans;
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
//memset(in,0,sizeof(in));
for(int i=1;i<=m;i++)
{
in[i]=0;//初始化数组
edge[i].clear();//清空vector
}
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
edge[y].push_back(x);//建图
in[x]++;//统计入度
}
//topo();
printf("%d\n",topo());
}
return 0;
}