HDU 2647 Reward

描述

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.

输入

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.

输出

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.

样例输入

2 1
1 2
2 2
1 2
2 1

样例输出

1777
-1

 

拓扑排序~~~可以存在单个独立点。(一直没有考虑到!)

发现反向建图能够很快的实现。

 

#include <stdio.h>
#include <string.h>
#include <queue>
#include <iostream>
#define MAXN 11000
using namespace std;

int n,m,cnt;
int head[MAXN];
int indgree[MAXN];
int flag[MAXN];
struct EdgeNode{
    int to;
    int next;    
}edge[MAXN*2];

struct INT{
    int nod;
    int step;
};

void addedge(int u, int v){
    edge[cnt].to=v;
    edge[cnt].next=head[u];
    indgree[v]++;
    head[u]=cnt++;
}

void topsort(){
    queue<INT> Q;
    int iq=0;
    for(int i=1; i<=n; i++){
        if(indgree[i]==0){
            INT t;
            t.nod=i;
            t.step=0; 
            Q.push(t);
        }
    }
    while(!Q.empty()){
        INT now=Q.front();
        Q.pop();
        flag[iq++]=now.step+888;
        for(int k=head[now.nod]; k!=-1; k=edge[k].next){
            indgree[edge[k].to]--;
            if(indgree[edge[k].to]==0){
                INT t;
                t.nod=edge[k].to;
                t.step=now.step+1;
                Q.push(t);
            }
        }        
    }
    if(iq>=n){
        int sum=0;
        for(int i=0; i<n; i++)
            sum+=flag[i];    
        printf("%d\n",sum);
    }else{
        printf("-1\n");
    }
}
int main(int argc, char *argv[])
{
    int u,v;
    while(scanf("%d %d" ,&n ,&m)!=EOF){
        cnt=0;
        memset(head,-1,sizeof(head));
        memset(indgree,0,sizeof(indgree));
        for(int i=1; i<=m; i++){
            scanf("%d%d",&u,&v);
            addedge(v,u);
        }
        topsort();
    }
    return 0;
}

 

你可能感兴趣的:(HDU)