码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2135:Farm Tour

时间:2014-10-09 00:53:07      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

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

#include <iostream>
#include <queue>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <stdio.h>
#define inf 0x3f3f3f3f
using namespace std;
int n,m,s,t,tt,head[1010],dis[1010],v[1010],pre[1010];
struct node
{
    int x,y,c,w;
    int next;
} eg[40001];
void init()
{
    tt=0;
    memset(head,-1,sizeof(head));
}
void add(int xx,int yy,int cc,int ww)
{
    eg[tt].x=xx;
    eg[tt].y=yy;
    eg[tt].c=cc;
    eg[tt].w=ww;
    eg[tt].next=head[xx];
    head[xx]=tt++;
    eg[tt].x=yy;
    eg[tt].y=xx;
    eg[tt].c=0;
    eg[tt].w=-ww;
    eg[tt].next=head[yy];
    head[yy]=tt++;
}
int spfa(int s,int t)
{
    for(int i=0; i<=t; i++)
    {
        v[i]=0;
        dis[i]=inf;
        pre[i]=-1;
    }
    queue<int>q;
    q.push(s);
    dis[s]=0;
    while(!q.empty())
    {
        int f=q.front();
        q.pop();
        v[f]=0;
        for(int i=head[f]; i!=-1; i=eg[i].next)
        {
            int w1=eg[i].y;
            if(eg[i].c&&dis[w1]>dis[f]+eg[i].w)
            {
                dis[w1]=dis[f]+eg[i].w;
                pre[w1]=i;
                if(!v[w1])
                {
                    v[w1]=1;
                    q.push(w1);
                }
            }
        }
    }
    if(dis[t]==inf)
    {
        return 0;
    }
    return 1;
}
void KM(int s,int t)
{
    int min1,ans=0;
    while(spfa(s,t)==1)
    {
        min1=inf;
        for(int i=pre[t]; i!=-1; i=pre[eg[i].x])
        {
            if(min1>=eg[i].c)
            {
                min1=eg[i].c;
            }
        }
        for(int i=pre[t]; i!=-1; i=pre[eg[i].x])
        {
            eg[i].c-=min1;
            eg[i+1].c+=min1;
        }
        ans+=min1*dis[t];
    }
    printf("%d\n",ans);
    return ;
}
int main()
{
    int xx,yy,zz;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        s=0;
        t=n+1;
        add(s,1,2,0);
        add(n,t,2,0);
        while(m--)
        {
            scanf("%d%d%d",&xx,&yy,&zz);
            add(xx,yy,1,zz);
            add(yy,xx,1,zz);
        }
        KM(s,t);
    }
    return 0;
}

 

POJ2135:Farm Tour

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/zhangmingcheng/p/4011862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!