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.
题意:使用最少的资金给每个人发工资且要求有等级,所以每次高一个level就多加1块,使用拓扑排序就能解决,但注意这题重要的一点是等级并列的情况,也就是工资相同。
拓扑排序算法要求图中存在入度为0的点,也就是不能是环或圈
拓扑排序算法过程是:1.设置一个数组保存每个点的入度
2.找到一个入度为0的点,将他的边删除,同时这条边所指向的另一个点入度-1
3.删除后,肯定会出现入度为0的点,因此重复1,2.
而这道题需要算出最少工资,因此再设置一个数组来记录每个员工的工资,然后在删除边时,让当前点所指向的点(相邻点)的工资等于自己+1
Sample Input
2 1
1 2
2 2
1 2
2 1
Sample Output
1777
-1
#include <stdio.h>
#include <vector>
#include <queue>
const int maxn = 20000 + 10;
using namespace std;
int in[maxn];
vector<int> gra[maxn];
int sum[maxn];
int tou(int n)
{
int u;
queue<int> q;
//1.找度数为0的点,放入队列
for(int j=1;j<=n;j++)
{
if(in[j]==0)
{
u=j;
sum[u]=888;
in[j]--;//同时记得对度数为0的点标记,保证不会被重复遍历
q.push(j);
}
}
while(!q.empty())
{
int u=q.front();
q.pop();
for(size_t j=0;j<gra[u].size();j++)
{
int to=gra[u][j];
in[to]--;
if(in[to]==0)
{
q.push(to);
in[to]--;
//让当前点所指向的点(相邻点)的工资等于自己+1
sum[to]=sum[u]+1;
}
}
}
int s=0;
for(int i=1;i<=n;i++)
{
if(in[i]!=-1) return -1;
s+=sum[i];
}
return s;
}
void init(int n)
{
for (int i = 0; i <= n; i++)
{
gra[i].clear();
in[i] = 0;
}
}
int main()
{
int n, m;
while (scanf("%d %d", &n, &m) != EOF)
{
init(n);
for (int i = 0; i < m; i++)
{
int u, t;
scanf("%d %d", &u, &t);
gra[t].push_back(u);
in[u]++;
}
int s=tou(n);
printf("%d\n",s);
}
}