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
题意:
一:不能在用简单的拓扑了,因为此时显然超内存。(此题内存只能开8000000的数组,不能开到一千万)只能用到邻接表。
二:注意多劳多得,可能前面的一个人后面跟着好几个,即,后面那几个人的工资是一样的
最后题意简单,就是叫你判读是否有环。
///@zhangxiaoyu
///2015/8/10
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<stack>
#include<queue>
#include<cmath>
#include<iostream>
using namespace std;
#define INF 0x7f7f7f
#define maxn 1000005
int in[10010],x[10010],money[10010];
int len,num;
int n,m;
vector<int>E[10010];
void init()
{
for(int i=1;i<=n;i++)
{
in[i]=0;
E[i].clear();
money[i]=888;
}
len=0;
num=0;
}
void topsort()///vector版本的拓扑排序模板
{
int j;
priority_queue<int,vector<int>,greater<int> >qq;///最小堆优队
for(int i=1;i<=n;i++)
{
if(in[i]==0)
qq.push(i);
}
while(!qq.empty())
{
j=qq.top();
qq.pop();
num++;
x[++len]=j;
for(int i=0;i<E[j].size();i++)
{
int k=E[j][i];
in[k]--;
if(money[j]+1>money[k])
money[k]=money[j]+1;///求最少的钱,又后边的奖金比前面大,故贪心的加1就是最少的
if(in[k]==0)
qq.push(k);
}
}
}
int main()
{
int x,y;
while(~scanf("%d%d",&n,&m))
{
init();
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
E[y].push_back(x);
in[x]++;
}
topsort();
if(num<n)
printf("-1\n");
else
{
int ans=0;
for(int i=1;i<=n;i++)
{
ans+=money[i];
}
printf("%d\n",ans);
}
}
return 0;
}