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

HDU2426:Interesting Housing Problem(还没过,貌似入门题)

时间:2014-10-11 00:14:04      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   for   sp   div   on   

#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define inf 1000001
using namespace std;
struct node
{
    int x,y,c,w;
    int next;
} eg[400001];
int n,m,K,s,t,tt,head[2005],dis[2005],pre[2005],v[2005];
void init()
{
    memset(head,-1,sizeof(head));
    tt=0;
    s=0;
    t=n+m+1;
}
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=s; 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 minx,ans=0,V=0;
    while(spfa(s,t)==1)
    {
        minx=inf;
        for(int i=pre[t]; i!=-1; i=pre[eg[i].x])
        {
            minx=min(minx,eg[i].c);
        }
        for(int i=pre[t]; i!=-1; i=pre[eg[i].x])
        {
            eg[i].c-=minx;
            eg[i+1].c+=minx;
        }
        V+=minx;
        ans+=minx*dis[t];
    }
    if(V>=n)
        printf("%d\n",-ans);
    else printf("-1\n");
    return ;
}
int main()
{
    int xx,yy,zz,T=0;
    while(scanf("%d%d%d",&n,&m,&K)!=EOF)
    {
        init();
        while(K--)
        {
            scanf("%d%d%d",&xx,&yy,&zz);
            xx++;
            yy++;
            if(zz<0)continue;
            add(xx,yy+n,1,-zz);
        }
        for(int i=1; i<=n; i++)
        {
            add(s,i,1,0);
        }
        for(int j=n+1; j<=n+m; j++)
        {
            add(j,t,1,0);
        }
        printf("Case %d: ",++T);
        KM(s,t);
    }
    return 0;
}

 

HDU2426:Interesting Housing Problem(还没过,貌似入门题)

标签:style   blog   color   io   os   for   sp   div   on   

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

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