poj2135
poj2135
根本想不到系列
求1到n,和n到1的最短路,但是不能重复走。
超级源点连到1,流量为2,费用为0;n连到超级汇点,流量为2,费用为0。
其他的流量为1,费用为边的长度。(图中为双向边
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 100010 #define For(i,a,b) for(int i=a;i<=b;i++) #define p(a) putchar(a) #define g() getchar() using namespace std; int n,m,s,t,x,y,v,w,maxflow,mincost,tot; int head[N],pre[N],last[N],flow[N],d[N]; bool vis[N]; struct node{ int n; int v; int w; int next; }e[N]; queue<int>q; void in(int &x){ int y=1; char c=g();x=0; while(c<'0'||c>'9'){ if(c=='-')y=-1; c=g(); } while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=g(); } x*=y; } void o(int x){ if(x<0){ p('-'); x=-x; } if(x>9)o(x/10); p(x%10+'0'); } void push(int x,int y,int v,int w){ e[tot].n=y; e[tot].v=v; e[tot].w=w; e[tot].next=head[x]; head[x]=tot++; } bool spfa(int s,int t){ memset(d,0x7f,sizeof(d)); memset(flow,0x7f,sizeof(flow)); memset(vis,0,sizeof(vis)); q.push(s); vis[s]=1; d[s]=0; pre[t]=-1; while(!q.empty()){ int now=q.front(); q.pop(); vis[now]=0; for(int i=head[now];i!=-1;i=e[i].next) if(e[i].v>0&&d[e[i].n]>d[now]+e[i].w){ d[e[i].n]=d[now]+e[i].w; pre[e[i].n]=now; last[e[i].n]=i; flow[e[i].n]=min(flow[now],e[i].v); if(!vis[e[i].n]){ vis[e[i].n]=1; q.push(e[i].n); } } } return pre[t]!=-1; } void MCMF(int s,int t){ while(spfa(s,t)){ int now=t; maxflow+=flow[t]; mincost+=flow[t]*d[t]; while(now!=s){ e[last[now]].v-=flow[t]; e[last[now]^1].v+=flow[t]; now=pre[now]; } } } int main(){ in(n);in(m); s=0;t=n+1; memset(head,-1,sizeof(head)); For(i,1,m){ in(x);in(y);in(w); push(x,y,1,w); push(y,x,0,-w); push(y,x,1,w); push(x,y,0,-w); } push(0,1,2,0); push(1,0,0,0); push(n,t,2,0); push(t,n,0,0); MCMF(s,t); o(mincost); return 0; }