【hdu 2647 C - 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



题意:

n个人,m条边,每条边a,b 表示a比b的工资多1,每个人的工资至少888,问你工资和至少多少?如果出现矛盾关系,输出-1

分析:拓扑排序,队列处理出层数。注意偏序顺序从层数小的到层数大的,错了好几次

多说一句,拓扑排序很多时候要考虑去重

代码:

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include<bitset>
#include <list>
#include <numeric>
#include <sstream>
#include <limits>
#define CLR(a, b) memset(a, (b), sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = acos(-1.0);
const double E = exp(1.0);
const double eps = 1e-30;

const double INFD = 1e20;
const ll INFLL = 0x3f3f3f3f3f3f3f3fll;
const int INF = 0x3f3f3f3f;
const int maxn = (int)1e4+8;
const int MAXN = (int)1e2 + 10;
const int MOD = (int)1e9 + 7;

vector<int>v[maxn];
int du[maxn];
int vis[maxn];
int layer[maxn];
long long ans=0;
int n,m;
int add=0;

int judge(void){
	int num=0;
	int flag=1;
	queue<int>q;
	for(int i=1;i<=n;i++){
		if(du[i]==0){
			q.push (i);
			layer[i]=0;
		}
	}
	while(!q.empty ()){
		int tmp=q.front ();q.pop();
		num++;
		ans+=layer[tmp]+888;
		for(int i=0;i<v[tmp].size ();i++){
			int j=v[tmp][i];
			if(du[j]&&!vis[j]){
				du[j]--;
				if(du[j]==0){
					vis[j]=1;
					layer[j]=layer[tmp]+1;
					q.push (j);
				}
			}
		}
	}
	return num==n;
}

int main(){
	while(~scanf("%d%d",&n,&m)){
		add=0;
		ans=0;
		CLR(vis,0);
		CLR(du,0);
		CLR(layer,-1);
		while(m--){
			int x,y;
			scanf("%d%d",&x,&y);
			v[y].push_back (x);
			du[x]++;
		}
		if(judge()){
			printf("%lld\n",ans);
		}else printf("%d\n",-1);
		for(int i=1;i<=n;i++)v[i].clear ();
	}
}

猜你喜欢

转载自blog.csdn.net/running_acmer/article/details/80992326