luogu2050 [NOI2012]美食节

修车加强版
边跑边加,有个师傅做到第 i 个(相对他自己而言),就给他加到 i+1 个。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, p, ss, tt, uu, hea[85005], cnt, tim[45][105], minCost;
int dis[85005], pre[85005], sf[85005], diji[85005];
const int oo=0x3f3f3f3f;
bool vis[85005];
queue<int> d;
int f(int i, int j){
	return (i-1)*p+j;
}
struct Edge{
	int too, nxt, val, cst;
}edge[3000005];
void add_edge(int fro, int too, int val, int cst){
	edge[cnt].nxt = hea[fro];
	edge[cnt].too = too;
	edge[cnt].val = val;
	edge[cnt].cst = cst;
	hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int cst){
	add_edge(fro, too, val, cst);
	add_edge(too, fro, 0, -cst);
}
bool spfa(){
	memset(dis, 0x3f, sizeof(dis));
	memset(pre, -1, sizeof(pre));
	d.push(ss);
	vis[ss] = true;
	dis[ss] = 0;
	while(!d.empty()){
		int x=d.front();
		d.pop();
		vis[x] = false;
		for(int i=hea[x]; i!=-1; i=edge[i].nxt){
			int t=edge[i].too;
			if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
				dis[t] = dis[x] + edge[i].cst;
				pre[t] = i;
				if(!vis[t]){
					vis[t] = true;
					d.push(t);
				}
			}
		}
	}
	return dis[tt]!=oo;
}
void mcmf(){
	while(spfa()){
		int tmp=oo, qwq;
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
			tmp = min(tmp, edge[i].val);
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
			edge[i].val -= tmp;
			edge[i^1].val += tmp;
			minCost += tmp * edge[i].cst;
		}
		qwq = edge[pre[tt]^1].too;
		addEdge(qwq+1, tt, 1, 0);
		for(int i=1; i<=n; i++)
			addEdge(i, qwq+1, 1, (diji[qwq]+1)*tim[i][sf[qwq]]);
	}
}
int main(){
	memset(hea, -1, sizeof(hea));
	cin>>n>>m;
	ss = 0;
	for(int i=1; i<=n; i++){
		scanf("%d", &uu);
		p += uu;
		addEdge(ss, i, uu, 0);
	}
	tt = n + m * p + 1;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++){
			scanf("%d", &tim[i][j]);
			addEdge(i, f(j,1)+n, 1, tim[i][j]);
		}
	for(int i=1; i<=m; i++)
		addEdge(f(i,1)+n, tt, 1, 0);
	for(int i=1; i<=m; i++)
		for(int j=1; j<=p; j++){
			sf[f(i,j)+n] = i;
			diji[f(i,j)+n] = j;
		}
	mcmf();
	cout<<minCost<<endl;
	return 0;
}
posted @ 2018-01-16 20:17  poorpool  阅读(122)  评论(0编辑  收藏  举报