poj3068 "Shortest" pair of paths 费用流

找两条总权值最小的互不相交的从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 200002
using 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值