【洛谷2050】 [NOI2012]美食节(费用流)

大家可以先看这道题目再做!
SCOI2007修车

传送门

洛谷

Solution

就和上面那道题目一样的套路,但是发现你会获得60~80分的好成绩!!!
考虑优化,因为是SPFA,所以每一次只会走最短路,做完之后发现。。。
欸,好像每一次会搞掉一条边,那么我们动态加入点就好了。

代码实现

/*
  mail: mleautomaton@foxmail.com
  author: MLEAutoMaton
  This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi()
{
    int f=1,sum=0;char ch=getchar();
    while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
    return f*sum;
}
int m,n,s,t,T[50][110],sum,p[110];
queue<int>Q;
const int N=100010,Inf=1e9+10;
struct node
{
    int to,nxt,w,c;
}e[5000010];
int front[N],cnt,dis[N],vis[N],fa[N],from[N];
int meal[N],cook[N];
void Add(int u,int v,int flow,int cost)
{
    e[cnt]=(node){v,front[u],flow,cost};front[u]=cnt++;
    e[cnt]=(node){u,front[v],0,-cost};front[v]=cnt++;
}
bool SPFA()
{
    memset(dis,63,sizeof(dis));
    Q.push(s);dis[s]=0;
    while(!Q.empty())
    {
        int u=Q.front();Q.pop();vis[u]=0;
        for(re int i=front[u];i!=-1;i=e[i].nxt)
        {
            int v=e[i].to;
            if(e[i].w && dis[v]>dis[u]+e[i].c)
            {
                dis[v]=dis[u]+e[i].c;fa[v]=u,from[v]=i;
                if(!vis[v])Q.push(v),vis[v]=1;
            }
        }
    }
    return dis[t]!=dis[t+1];
}
int McMf()
{
    int cost=0;
    while(SPFA())
    {
        int di=Inf;
        for(re int i=t;i!=s;i=fa[i])di=min(di,e[from[i]].w);
        cost+=di*dis[t];
        for(re int i=t;i!=s;i=fa[i])
            e[from[i]].w-=di,e[from[i]^1].w+=di;
        int Last=fa[t];Last++;
        for(re int i=1;i<=n;i++)
            Add(i,Last,1,meal[Last]*T[i][cook[Last]]);
        Add(Last,t,1,0);
    }
    return cost;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.in","r",stdin);
#endif
    memset(front,-1,sizeof(front));
    n=gi();m=gi();
    for(re int i=1;i<=n;i++)p[i]=gi(),sum+=p[i];
    for(re int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            T[i][j]=gi();
    for(re int i=1;i<=n;i++)
        Add(s,i,p[i],0);
    t=m*sum+n+1;
	for(re int i=1;i<=n;i++)
		for(re int j=1;j<=m;j++)
			for(re int k=1;k<=sum;k++)
			{
				cook[(j-1)*sum+k+n]=j;
				meal[(j-1)*sum+k+n]=k;
			}
    for(re int i=1;i<=n;i++)
        for(re int j=1;j<=m;j++)
            Add(i,(j-1)*sum+1+n,1,T[i][j]);
    for(re int i=n+1;i<t;i+=sum)
        Add(i,t,1,0);
    printf("%d\n",McMf());
    return 0;
}
posted @ 2019-03-18 15:19  QwQGJH  阅读(130)  评论(0编辑  收藏  举报