洛谷4014分配问题

题目链接:分配问题

这题比运输问题还裸啊

费用流模板题

#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<vector>
#include<queue>
#include<map>
using namespace std;
#define rep(i,a,b) for (i=a;i<=b;i++)
typedef long long ll;
#define maxd 1e9+7

struct node{
    int to,nxt,cost,flow;
}sq[100100];
int n,m,all=1,dis[100100],pre[100100],head[100100],s,t,maxf=0,minc=0,mp[110][110],flow[100100];
bool vis[100100];
void add(int u,int v,int f,int w)
{
    all++;sq[all].to=v;sq[all].nxt=head[u];sq[all].cost=w;sq[all].flow=f;head[u]=all;
    all++;sq[all].to=u;sq[all].nxt=head[v];sq[all].cost=-w;sq[all].flow=0;head[v]=all;
}

bool spfa()
{
    queue<int> q;int i;
    for (i=1;i<=t;i++) dis[i]=maxd;dis[s]=0;
    memset(vis,0,sizeof(vis));
    memset(flow,0,sizeof(flow));
    vis[s]=1;q.push(s);flow[s]=maxd;
    while (!q.empty())
    {
        int u=q.front();q.pop();vis[u]=0;
        for (i=head[u];i;i=sq[i].nxt)
        {
            int v=sq[i].to;
            if ((sq[i].flow) && (dis[v]>dis[u]+sq[i].cost))
            {
                dis[v]=sq[i].cost+dis[u];pre[v]=i;
                flow[v]=min(flow[u],sq[i].flow);
                if (!vis[v])
                {
                    vis[v]=1;q.push(v);
                }
            }
        }
    }
    return (dis[t]!=maxd);
}

void update()
{
    int now=t;
    maxf+=flow[t];
    minc+=(flow[t]*dis[t]);
    while (now!=s)
    {
        int tmp=pre[now];
        sq[tmp].flow-=flow[t];
        sq[tmp^1].flow+=flow[t];
        now=sq[tmp^1].to;
    }
}

int read()
{
    int x=0,f=1;char ch=getchar();
    while ((ch<'0') || (ch>'9')) {if (ch=='-') f=-1;ch=getchar();}
    while ((ch>='0') && (ch<='9')) {x=x*10+(ch-'0');ch=getchar();}
    return x*f;
}

void init()
{
    n=read();s=n*2+1;t=n*2+2;
    int i,j;
    for (i=1;i<=n;i++)
    {
        for (j=1;j<=n;j++) mp[i][j]=read();
    }
}

void init_max()
{
    int i,j;all=1;
    memset(head,0,sizeof(head));
    for (i=1;i<=n;i++)
    {
        for (j=1;j<=n;j++)
        {
            add(i,j+n,1,-mp[i][j]);
        }
        add(s,i,1,0);
        add(i+n,t,1,0);
    }
}

void init_min()
{
    int i,j;all=1;
    memset(head,0,sizeof(head));
    for (i=1;i<=n;i++)
    {
        for (j=1;j<=n;j++)
        {
            add(i,j+n,1,mp[i][j]);
        }
        add(s,i,1,0);
        add(i+n,t,1,0);
    }
}

void work(int fu)
{
    maxf=0;minc=0;
    while (spfa()) update();
    printf("%d\n",minc*fu);
}

int main()
{
    init();
    init_min();
    work(1);
    init_max();
    work(-1);
    return 0;
}
posted @ 2018-12-27 00:12  EncodeTalker  阅读(206)  评论(0编辑  收藏  举报