程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> POJ 1637 Sightseeing tour 混合圖歐拉回路 最大流

POJ 1637 Sightseeing tour 混合圖歐拉回路 最大流

編輯:關於C++

題目大意:給出一張混合圖,問是否存在歐拉回路。

 

思路:成題,直接看題解吧。

 

 

CODE:
 

#include 
#include 
#include 
#include 
#include 
#define MAX 510
#define MAXE 5000000
#define INF 0x3f3f3f3f
#define S 0
#define T (MAX - 1)
using namespace std;
#define min(a,b) ((a) < (b) ? (a):(b))
#define max(a,b) ((a) > (b) ? (a):(b))

struct Edge{
	int x,y;
	bool directed;
	
	void Read() {
		int z;
		scanf(%d%d%d,&x,&y,&z);
		directed = z;
	}
}edge[MAXE];

struct MaxFlow{
	int head[MAX],total;
	int next[MAXE],aim[MAXE],flow[MAXE];
	
	int deep[MAX];
	
	void Initialize() {
		total = 1;
		memset(head,0,sizeof(head));
	}
	void Add(int x,int y,int f) {
		next[++total] = head[x];
		aim[total] = y;
		flow[total] = f;
		head[x] = total;
	}
	void Insert(int x,int y,int f) {
		Add(x,y,f);
		Add(y,x,0);
	}
	bool BFS() {
		static queue q;
		while(!q.empty())	q.pop();
		memset(deep,0,sizeof(deep));
		deep[S] = 1;
		q.push(S);
		while(!q.empty()) {
			int x = q.front(); q.pop();
			for(int i = head[x]; i; i = next[i])
				if(flow[i] && !deep[aim[i]]) {
					deep[aim[i]] = deep[x] + 1;
					q.push(aim[i]);
					if(aim[i] == T)	return true;
				}
		}
		return false;
	}
	int Dinic(int x,int f) {
		if(x == T)	return f;
		int temp = f;
		for(int i = head[x]; i; i = next[i])
			if(deep[aim[i]] == deep[x] + 1 && flow[i] && temp) {
				int away = Dinic(aim[i],min(flow[i],temp));
				flow[i] -= away;
				flow[i^1] += away;
				temp -= away;
			}
		return f - temp;
	}
}solver;

int _T;
int points,edges;
int in[MAX],out[MAX];

int sum;

inline bool Euler()
{
	sum = 0;
	for(int i = 1; i <= points; ++i) {
		int degree = out[i] - in[i];
		if(degree&1)	return false;
		degree >>= 1;
		if(degree > 0)	solver.Insert(S,i,degree),sum += degree;
		else	solver.Insert(i,T,-degree);
	}
	return true;
}

int main()
{
	for(cin >> _T; _T--;) {
		solver.Initialize();
		memset(in,0,sizeof(in));
		memset(out,0,sizeof(out));
		scanf(%d%d,&points,&edges);
		for(int i = 1; i <= edges; ++i) {
			edge[i].Read();
			if(edge[i].x == edge[i].y)	continue;
			if(!edge[i].directed)	solver.Insert(edge[i].x,edge[i].y,1);
			++in[edge[i].y],++out[edge[i].x];
		}
		if(!Euler()) {
			puts(impossible);
			continue;
		}
		int max_flow = 0;
		while(solver.BFS())
			max_flow += solver.Dinic(S,INF);
		if(max_flow == sum)	puts(possible);
		else	puts(impossible);
	}
	return 0;
}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved