poj3068 "Shortest" pair of paths 费用流

来源:互联网 发布:红辣椒乐队 知乎 编辑:程序博客网 时间:2024/05/29 17:57

找两条总权值最小的互不相交的从1到n的路径,最小费用流。


#include <iostream>#include <cstring>#include <cstdlib>#include <cmath>#include <vector>#include <queue>#include <cstdio>#include <utility>#include <algorithm>#define N 5005#define M 200002using namespace std;int s, t , ans , maxflow;int pre[N] , mcnt;struct arc{  int x , f , c , next;}e[M];void addarc(int x ,int y ,int z ,int c){  e[mcnt] = (arc){y , z , c , pre[x]} , pre[x] = mcnt ++;  e[mcnt] = (arc){x , 0 , -c , pre[y]} , pre[y] = mcnt ++;  // printf("%d %d %d %d\n",x,y,z,c);}int d[N] , p[N];bool f[N];deque<int> q;bool Bellman_Ford(){  int i , x , y , z;  memset(f , 0 , sizeof(f));  for (i = 1; i <= t ; ++ i) d[i] = 1 << 30;  d[s] = 0 , f[s] = 1 , q.push_back(s);  while (!q.empty())  {    x = q.front() , q.pop_front() , f[x] = 0;    for (i = pre[x] ; ~i ; i = e[i].next)    {      y = e[i].x , z = e[i].c;      if (e[i].f && d[y] > d[x] + z)      {        d[y] = d[x] + z , p[y] = i;        if (!f[y])        {          if (q.empty() || d[y] < d[q.front()])            q.push_front(y);          else q.push_back(y);          f[y] = 1;        }      }    }  }  return d[t] != 1 << 30;}int Mincostflow(){  maxflow = 0 , ans = 0;  int x;  while (Bellman_Ford())  {    int flow = 1 << 30;    for (x = t ; x != s ; x = e[p[x] ^ 1].x)      flow = min(flow , e[p[x]].f);    maxflow += flow , ans += d[t] * flow;    for (x = t ; x != s ; x = e[p[x] ^ 1].x)      e[p[x]].f -= flow , e[p[x] ^ 1].f += flow;  }  return ans;}int n , m , ca;void work(){  printf("Instance #%d: " , ++ ca);  int x , y , z;  memset(pre , -1 , sizeof(pre)) , mcnt = 0;  ans = maxflow = 0 , s = n + 1 , t = s + 1;  addarc(s , 1 , 2 , 0) , addarc(n , t , 2 , 0);  while (m --)  {    scanf("%d%d%d",&x,&y,&z) , ++ x , ++ y;    addarc(x , y , 1 , z);  }  Mincostflow();  if (maxflow < 2)    puts("Not possible");  else printf("%d\n" , ans);}int main(){  while(scanf("%d%d", &n,&m) , n || m)  //int _;cin>>_;while(_--)    work();  return 0;}


原创粉丝点击