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

复制代码
#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;
}
复制代码

 

posted @   人艰不拆_zmc  阅读(263)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示