@Chilling
2017-02-16T17:54:58.000000Z
字数 1963
阅读 844
拓扑排序
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
题意:输入n和m,代表有n个人,以下有m行需求,每行两个数字x和y,表示x的奖金要比y的奖金高,最低的奖金是888元,求能满足所有人的需求的最小奖金。
分析:这道题数据比较多,最好用邻接表来存。将x作为入度,y作为出度,入度为0说明只有基础奖励888元。
比如1>2,2>3,3>4,存入的时候in[1]++,in[2]++,in[3]++,4这个人入度为0,就只有基础奖金。
void topsort()
{
queue<int>q;
for(int i=1;i<=n;i++) //找出入度为0的点
{
if(in[i]==0)
{
pay[i]=888;
q.push(i);
}
}
s=0;
while(!q.empty())
{
int now=q.front();
q.pop();
s++;
int l=v[now].size();
for(int i=0;i<l;i++)
{
int k=v[now][i];
in[k]--;
if(in[k]==0)
{
q.push(k);
pay[k]=pay[now]+1; //比前一个人的奖金多1元
}
}
}
if(s<n) flag=0;
}
#include<stdio.h>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
vector<int>v[10005];
int in[10005],pay[10005];
int n,m,s,flag;
void topsort()
{
queue<int>q;
for(int i=1;i<=n;i++)
{
if(in[i]==0)
{
pay[i]=888;
q.push(i);
}
}
s=0;
while(!q.empty())
{
int now=q.front();
q.pop();
s++;
int l=v[now].size();
for(int i=0;i<l;i++)
{
int k=v[now][i];
in[k]--;
if(in[k]==0)
{
q.push(k);
pay[k]=pay[now]+1;
}
}
}
if(s<n) flag=0;
}
int main()
{
int i,x,y,sum;
while(scanf("%d%d",&n,&m)!=EOF)
{
flag=1,sum=0;
memset(in,0,sizeof(in));
memset(pay,0,sizeof(pay));
for(i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
v[y].push_back(x);
in[x]++;
}
topsort();
if(flag==0)
printf("-1\n");
else
{
for(i=1;i<=n;i++)
sum+=pay[i];
printf("%d\n",sum);
}
for(i=1;i<=n;i++)
v[i].clear();
}
return 0;
}