拓扑排序 hdu 2647 Reward

来源:互联网 发布:三星电话交换机编程 编辑:程序博客网 时间:2024/06/06 07:04
2011ACM/ICPC亚洲区中国大陆5个赛区信息汇集

Reward

TimeLimit: 2000/1000 MS(Java/Others)    MemoryLimit: 32768/32768 K (Java/Others)
Total Submission(s):868    AcceptedSubmission(s): 260


Problem Description
Dandelion's uncle is a boss of a factory. As the spring festival iscoming , he wants to distribute rewards to his workers. Now he hasa trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may havedemands of the distributing of rewards ,just like a's reward shouldmore 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 willbe at least 888 , because it's a lucky number.
 

Input
One line with two integers n and m ,stands for the number of worksand the number of demands.(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands fora's reward should be more than b's.
 

Output
For every case ,print the least money dandelion 's uncle needs todistribute .If it's impossible to fulfill all the works' demands,print -1.
 

Sample Input
21 
12 
22 
12 
21
 

Sample Output
1777 
-1
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node
{
    intdata;
    structnode *next;
};
int getmax(int a,int b)
{
return a>b?a:b;
}

struct node a[10010];  
int flag=1;
int mon[10010]; 
void  Topsort(int T)
{
    int i,sum=0,j;  
  for(i=1;i<=T;i++)
  {
struct node *p;
j=1;
while(a[j].data!=0) j++;
if(j>T)  flag=0;  
  sum+=mon[j];
 a[j].data=-1;
for(p = a[j].next;p!=NULL;p=p->next)
{
a[p->data].data --;
mon[p->data]=getmax(mon[j]+1,mon[p->data]);
}
  }
if(flag==1)
printf("%d\n",sum);
else printf("-1\n");  
}

int main()
{
    intT,m,i,x,y;
   while(scanf("%d%d",&T,&m)!=EOF)
    {
flag=1;
memset(mon,0,sizeof(mon));
for(i=1;i<=T;i++)
       {
          a[i].data=0;
          a[i].next=NULL;
       }  
while(m--)
{
     
          struct node *q,*p;
          p=(struct node*)malloc(sizeof(structnode));
          scanf("%d%d",&x,&y);
if(x!=y)
{
a[x].data++;
p->data=x;
p->next=NULL;
q=&a[y];
if(q->next==NULL)
q->next=p;
else
{
p->next=q->next;
q->next=p;
                 
}
}
}
for(i=1;i<=T;i++)
{
mon[i]=888;
}
Topsort(T);
   
}
    
    return0;
}