UVA 10735 - Euler Circuit(最大流+欧拉回路)
题目链接 https://cn.vjudge.net/problem/UVA-10735
【题意】
给出一个V个点E条边的混合图(有的是有向边,有的是无向边)求出它的一条欧拉回路,如果没有输出无解信息,输入保证忽略边的方向后图是连通的(V<=100, E<=500)
【思路】
看了书上的讲解和其它题解感觉这种做法太强了,用最大流来调整结点的入度和出度,真的想不到,贴个题解
代码的细节也有很多
#include<bits/stdc++.h>
using namespace std;
const int inf=2e9;
const int maxn=120;
const int maxm=550;
struct Edge{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic{
int n,m,s,t;
vector<Edge> edges;
vector<int> g[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init(int n){
this->n=n;
for(int i=0;i<n;i++) g[i].clear();
edges.clear();
}
void add(int from,int to,int cap){
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0));
m=edges.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool BFS(){
memset(vis,0,sizeof(vis));
queue<int> que;
que.push(s);
d[s]=0;
vis[s]=1;
while(!que.empty()){
int x=que.front();que.pop();
for(int i=0;i<g[x].size();++i){
Edge& e=edges[g[x][i]];
if(!vis[e.to] && e.cap>e.flow){
vis[e.to]=1;
d[e.to]=d[x]+1;
que.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x,int a){
if(x==t || a==0) return a;
int flow=0,f;
for(int& i=cur[x];i<g[x].size();++i){
Edge& e=edges[g[x][i]];
if(d[x]+1==d[e.to] && (f=DFS(e.to,min(a,e.cap-e.flow)))>0){
e.flow+=f;
edges[g[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(a==0) break;
}
}
return flow;
}
int Maxflow(int s,int t){
this->s=s;this->t=t;
int flow=0;
while(BFS()){
memset(cur,0,sizeof(cur));
flow+=DFS(s,inf);
}
return flow;
}
};
Dinic dinic;
int n,m;
int degree[maxn];
bool used[maxm];
vector<Edge> edges;
vector<int> g[maxn],path;
void dfs(int u){
for(int i=0;i<g[u].size();++i){
int num=g[u][i];
if(!used[num]){
used[num]=true;
int v=edges[num].to;
dfs(v);
path.push_back(v);
}
}
}
void init(){
edges.clear();
path.clear();
for(int i=0;i<maxn;++i) g[i].clear();
memset(used,0,sizeof(used));
memset(degree,0,sizeof(degree));
dinic.init(maxn);
}
int main(){
int T;
scanf("%d",&T);
while(T--){
init();
scanf("%d%d",&n,&m);
for(int i=0;i<m;++i){
int u,v;
char tp[2];
scanf("%d%d%s",&u,&v,tp);
if(tp[0]=='D'){
edges.push_back(Edge(u,v,0,0));
g[u].push_back(edges.size()-1);
}
else dinic.add(u,v,1);
++degree[u],--degree[v];
}
bool ok=true;
int flow=0;
for(int i=1;i<=n;++i){
if(degree[i]&1){ok=false;break;}
if(degree[i]>0){
dinic.add(0,i,degree[i]/2);
flow+=degree[i]/2;
}
else dinic.add(i,maxn-1,-degree[i]/2);
}
if(ok){
if(dinic.Maxflow(0,maxn-1)!=flow) ok=false;
else{
for(int i=0;i<dinic.edges.size();++i){
Edge& e=dinic.edges[i];
if(e.from==0 || e.to==maxn-1) continue;
if(e.cap==0) continue;//有容量为0的反向边要过滤掉
if(e.flow==e.cap){//满流说明这条边应该反向,使得结点的出度减2
edges.push_back(Edge(e.to,e.from,0,0));
g[e.to].push_back(edges.size()-1);
}
else{
edges.push_back(Edge(e.from,e.to,0,0));
g[e.from].push_back(edges.size()-1);
}
}
}
}
if(ok){
dfs(1);
path.push_back(1);
for(int i=path.size()-1;i>=0;--i)
printf("%d%c",path[i],i==0?'\n':' ');
}
else puts("No euler circuit exist");
if(T) puts("");
}
return 0;
}