1. 程式人生 > >HDU-2647-Reward(拓撲排序-逆向建圖)

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.
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

#include <bits/stdc++.h>
using namespace std;
#define maxn 100005
queue<int>q;
vector<int>t[maxn];
int ans,sum[maxn],in[maxn];
void init()
{
    while(!q.empty())
        q.pop();
    for(int a = 0;a < maxn;a ++)
        t[a].clear();
    memset(in,0,sizeof(in));
    ans=0;
}
int main()
{
    int
n,m; while(scanf("%d%d",&n,&m)!=EOF) { init();//初始化操作 int u,v; for(int a = 0;a < m;a ++)//逆向建圖 { scanf("%d%d",&u,&v); u--,v--; in[u]++; t[v].push_back(u); } for(int a = 0;a < n;a ++) { if
(!in[a])//結點為0放入佇列中,並初始化該節點的值為888 { q.push(a); sum[a]=888; } } int cnt=0; while(!q.empty()) { cnt++; int p = q.front(); q.pop(); for(int a = 0;a < t[p].size();a ++)//通過該節點找出比下一個結點(比該節點大) { in[t[p][a]]--;//對於找到的入度為零的點,要讓其對應的弧頭入度減1 if(in[t[p][a]]==0)//結點為0就入隊 { q.push(t[p][a]); sum[t[p][a]]=sum[p]+1;//記錄下應該發的工資 } } } for(int a = 0;a < n;a ++) ans=ans+sum[a]; if(cnt!=n) ans=-1; printf("%d\n",ans); } return 0; }