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.
InputOne line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
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.
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.OutputFor 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 1Sample Output
1777
-1
题目意思:老板给员工发奖金,最少888,题目给出若干个a和b,代表a的奖金要比b的奖金多。
问所给关系合不合法(存不存在环),若合法,老板最少总共要发多少钱奖金?
直接拓扑排序判断是否合法,同时可以输出一组最优的序列。
若对拓扑排序不熟悉,请参考我写的一篇入门拓扑排序题的讲解。
https://blog.csdn.net/weixin_37622537/article/details/79913215
附AC代码:
//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<vector>
#include<stack>
#include<cstdio>
using namespace std;
#define up(i,j,k) for(int i=j;i<k;i++)
#define uup(i,j,k) for(int i=j;i>=k;i--)
#define mem(i,j) memset(i,j,sizeof i)
#define sfi(i) scanf("%d",&i)
#define sfl(i) scanf("%lld",&i)
#define sfd(i) scanf("%lf",&i)
#define sfc(i) scanf("%c",&i)
#define sfs(i) scanf("%s",i)
#define sf() cout<<"This is a flag!"<<endl;
#define wt(i) cout<<"This is "<<i<<endl;
#define ll long long
#define mod(x) (x)%mod
#define fre() freopen("d:\\1.txt","r",stdin)
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int MAX=1e4+50;
struct node //邻接矩阵
{
int v,nxt;
}p[2*MAX];
int head[MAX];
int du[MAX];
int t;
int n,m;
void add(int u,int v)
{
p[t].v=v;
p[t].nxt=head[u];
head[u]=t++;
}
int num[MAX];
int topo()
{
int sum=0;
int cnt=0;
int val=888;
for(int i=0;i<n;i+=cnt)
{
cnt=0;
up(j,1,n+1)
{
if(du[j]==0) //度为0说明当前状态图中,该点获得的奖金最少。
{
du[j]=-1; //将度置为-1可以防止下次再次选到
num[cnt++]=j;
}
}
if(cnt==0) //没找到度为0的点,即存在环,关系有误。
{
return -1;
}
sum+=cnt*val;
for(int j=0;j<cnt;j++)
{
for(int k=head[num[j]];k!=-1;k=p[k].nxt)
{
du[p[k].v]--;
}
}
val++; //每一次度减少1,发的钱就要多1。(满足题目要求,总额最少,同时满足a的奖金多于b的奖金)
}
return sum;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
mem(head,-1);
mem(du,0);
t=0;
int a,b;
up(i,0,m)
{
scanf("%d%d",&a,&b);
add(b,a); //反向建边,为了访问上一个点
du[a]++; //钱多的度+1;
}
printf("%d\n",topo());
}
return 0;
}