Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6090 Accepted Submission(s): 1874
Problem 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.
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.
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
思路:10000*10000用矩阵会超内存,用邻接表,将b作为出度,a作为入度,例如b——>a,奖金逐渐上升。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
#define MAX 10010
int head[MAX];
int in[MAX];//入度;
int reward[MAX];//奖金;
struct node
{
int to,next;
}edge[2*MAX];
int n,m;
int top;
queue<int>q;
void add(int a,int b)
{
edge[top].to=a;//将a当作头部;
edge[top].next=head[b];//将b当作尾部;
head[b]=top++;
}
int toposort()
{
int i;
for(i=1;i<=n;i++)
{
if(!in[i])//将所有入度为0的点放入队列;
{
q.push(i);
}
}
int sum=0,count=0,k=0;
while(!q.empty())
{
int u=q.front();
q.pop();
sum+=reward[u];//需要的奖金总和;
count++;//计数器;
for(k=head[u];k!=-1;k=edge[k].next)
{
//删除所有从顶点出发的有向边;
in[edge[k].to]--;
if(in[edge[k].to]==0)
//更新后的in,找到入度为0的点,加入到队列中;
{
q.push(edge[k].to);
reward[edge[k].to]=reward[u]+1;
}
}
}
if(count!=n)
sum=-1;
return sum;
}
int main()
{
int a,b,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
for(i=1;i<=n;i++)//至少888;
{
reward[i]=888;
}
top=0;
for(i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
//建立反向拓扑排序;
add(a,b);
in[a]++;//a的入度增加;
}
int ans=toposort();
printf("%d\n",ans);
}
return 0;
}