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
题目大意:
给定n个人,m个条件。
每个条件是两个整数a,b,代表两个人,要求a的奖金比b的奖金多。
并且每个人的奖金至少是888。
问奖金总额至少是多少。
核心思想:
拓扑排序。
每一次将所有入度为0的点一起取下,这些人的奖金数是一样的,都是前一批取下的人的奖金数+1。
一层一层的将点取下,全部取完就输出总额,无法取完(即含有环)就输出-1。
代码如下:
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e4+10;
vector<int>vec[N];
int ru[N];
bool vis[N];
ll ans;
bool TuoPu(int n)
{
queue<int>q;
int cnt=0;
ll z=888;
while(1)
{
int flag=0;
for(int i=1;i<=n;i++)
if(!vis[i]&&ru[i]==0)
{
vis[i]=1;
flag=1;
q.push(i);
cnt++;
}
if(!flag)
break;
ans+=z*q.size();
z++;
while(!q.empty())
{
int te=q.front();
q.pop();
int len=vec[te].size();
for(int i=0;i<len;i++)
ru[vec[te][i]]--;
}
}
if(cnt<n)
return 0;
return 1;
}
int main()
{
int n,m,x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
//初始化
for(int i=1;i<=n;i++)
{
vec[i].clear();
ru[i]=0;
vis[i]=0;
}
ans=0;
//输入
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
ru[x]++;
vec[y].push_back(x);
}
//拓扑并输出
if(!TuoPu(n))
printf("-1\n");
else
printf("%lld\n",ans);
}
return 0;
}