题目大意:给出一张混合图,问是否存在欧拉回路。
思路:成题,直接看题解吧。
http://www.cnblogs.com/Lyush/archive/2013/05/01/3052847.html
CODE:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#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<int> 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;
}