hdu2647拓扑排序(逆向)

思路:分层拓扑;

题目链接

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int n,m;
int in[10010];
vector<int> G[10010];
inline void Init(){
	MEM(in, 0);
	for (int i = 1;i <= n;i++)
		G[i].clear();
}
void Topo(){
	int cnt = 0;
	int times = 0;
	int sum = 0;
	bool flag = true;
	int ss = 888;
	while(true){
		queue<int> que;
		int rec = 0;
		for (int i = 1;i <= n;i++){
			if (in[i] == 0){
				que.push(i);
				in[i]--;
				cnt++;
				rec++;
				// cout << "i = " << i << endl;
			}
		}
		sum += (rec * ss);
		ss++;
		if (que.empty() && cnt < n) {
			flag = false;
			break;
		}
		if (cnt == n) break;
		while(!que.empty()){
			int u = que.front();
			que.pop();
			for (int i = 0;i < G[u].size();i++){
				int v = G[u][i];
				in[v]--;
			}
		}
		// sum += (rec * 888);
	}
	if (!flag) printf("-1\n");
	else printf("%d\n",sum);
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	while(~scanf("%d%d",&n,&m)){
		Init();
		int u,v;
		for (int i = 1;i <= m;i++){
			scanf("%d%d",&u,&v);
			in[u]++;
			G[v].push_back(u);
		}
		Topo();
	}
	return 0;
}
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/KIJamesQi/article/details/48602261
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞