POJ 1637 Sightseeing tour(混合图欧拉回路+最大流)

http://poj.org/problem?id=1637

题意:
给出n个点和m条边,这些边有些是单向边,有些是双向边,判断是否能构成欧拉回路。

思路:

构成有向图欧拉回路的要求是入度=出度,无向图的要求是所有顶点的度数为偶数。

但不管是那个,顶点的度数若是奇数,那都是不能构成的。

这道题目是非常典型的混合图欧拉回路问题,对于双向边,我们先随便定个向,然后就这样先记录好每个顶点的入度和出度。

如果有顶点的度数为奇数,可以直接得出结论,是不能构成欧拉回路的。

那么,如果都是偶数呢?

因为还会存在入度不等于出度的情况,那么这个时候就要通过改变改变双向边的方向来改变度数。对于每个顶点,如果出度大于入度,那么就将该点与源点相连,容量为(out-in)/2,代表需要改变几条双向边的方向,同理,如果入度大于出度,那么就将该点与汇点相连,容量为(in-out)/2。

那么,顶点之间如何连接呢?

对于双向边,将该两个顶点相连,容量为1,代表这条边可以反向一次

最后,走一遍最大流,如果满流,就说明能够构成欧拉回路。

 #include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
using namespace std;
typedef long long LL;
typedef pair<int,int> pll;
const int INF=0x3f3f3f3f;
const int maxn=+; struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int w,int f):from(u),to(v),cap(w),flow(f){}
}; struct Dinic
{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int cur[maxn];
int d[maxn]; void init(int n)
{
this->n=n;
for(int i=;i<n;++i) G[i].clear();
edges.clear();
} void AddEdge(int from,int to,int cap)
{
edges.push_back( Edge(from,to,cap,) );
edges.push_back( Edge(to,from,,) );
m=edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
} bool BFS()
{
queue<int> Q;
memset(vis,,sizeof(vis));
vis[s]=true;
d[s]=;
Q.push(s);
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=;i<G[x].size();++i)
{
Edge& e=edges[G[x][i]];
if(!vis[e.to] && e.cap>e.flow)
{
vis[e.to]=true;
d[e.to]=d[x]+;
Q.push(e.to);
}
}
}
return vis[t];
} int DFS(int x,int a)
{
if(x==t || a==) return a;
int flow=, f;
for(int &i=cur[x];i<G[x].size();++i)
{
Edge &e=edges[G[x][i]];
if(d[e.to]==d[x]+ && (f=DFS(e.to,min(a,e.cap-e.flow) ) )>)
{
e.flow +=f;
edges[G[x][i]^].flow -=f;
flow +=f;
a -=f;
if(a==) break;
}
}
return flow;
} int Maxflow(int s,int t)
{
this->s=s; this->t=t;
int flow=;
while(BFS())
{
memset(cur,,sizeof(cur));
flow +=DFS(s,INF);
}
return flow;
}
}DC; int in[maxn],out[maxn];
int u[maxn],v[maxn],w[maxn];
int n,m; int main()
{
//freopen("D:\\input.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
memset(in,,sizeof(in));
memset(out,,sizeof(out));
int src=,dst=n+;
DC.init(dst+); for(int i=;i<=m;i++)
{
scanf("%d%d%d",&u[i],&v[i],&w[i]);
out[u[i]]++;
in[v[i]]++;
} bool flag=true;
int full_flow=;
for(int i=;i<=n;i++)
{
if(((in[i]+out[i])&)) {flag=false;break;}
if(in[i]>out[i]) {DC.AddEdge(i,dst,(in[i]-out[i])/);full_flow+=(in[i]-out[i])/;}
if(out[i]>in[i]) DC.AddEdge(src,i,(out[i]-in[i])/);
} if(flag)
{
for(int i=;i<=m;i++)
if(!w[i]) DC.AddEdge(u[i],v[i],);
} if(flag)
{
int flow=DC.Maxflow(src,dst);
if(flow==full_flow) puts("possible");
else puts("impossible");
}
else puts("impossible");
}
return ;
}
上一篇:利用maven打jar包(项目来自GitHub)


下一篇:兼容ie6/ff/ch/op的div+css实现的圆角框