其他分享
首页 > 其他分享> > P3980 [NOI2008] 志愿者招募 题解

P3980 [NOI2008] 志愿者招募 题解

作者:互联网

P3980 [NOI2008] 志愿者招募

无源汇上下界最小费用流。

/*
{
######################
#       Author       #
#        Gary        #
#        2021        #
######################
*/
#include<bits/stdc++.h>
#define rb(a,b,c) for(int a=b;a<=c;++a)
#define rl(a,b,c) for(int a=b;a>=c;--a)
#define LL long long
#define IT iterator
#define PB push_back
#define II(a,b) make_pair(a,b)
#define FIR first
#define SEC second
#define FREO freopen("check.out","w",stdout)
#define rep(a,b) for(int a=0;a<b;++a)
#define SRAND mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define random(a) rng()%a
#define ALL(a) a.begin(),a.end()
#define POB pop_back
#define ff fflush(stdout)
#define fastio ios::sync_with_stdio(false)
#define check_min(a,b) a=min(a,b)
#define check_max(a,b) a=max(a,b)
using namespace std;
#define int LL
//inline int read(){
//    int x=0;
//    char ch=getchar();
//    while(ch<'0'||ch>'9'){
//        ch=getchar();
//    }
//    while(ch>='0'&&ch<='9'){
//        x=(x<<1)+(x<<3)+(ch^48);
//        ch=getchar();
//    }
//    return x;
//}
const LL INF=10000000000ll;
typedef pair<int,int> mp;
/*}
*/

const int GRAPH_SIZE= 1010;
int s=0,t=GRAPH_SIZE-1;
struct EDGE{
	int u,v,c,cos;
};
vector<EDGE> e;
vector<int> each[GRAPH_SIZE];
int maxflow,mincost;
int flow[GRAPH_SIZE];
int dis[GRAPH_SIZE],inq[GRAPH_SIZE],las[GRAPH_SIZE];
bool spfa(){
	memset(inq,0,sizeof(inq));
	memset(dis,127,sizeof(dis));
	flow[s]=INF;
	dis[s]=0;
	queue<int> q;
	q.push(s);
	inq[s]=1;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		inq[now]=0;
		for(auto it:each[now]){
			int to,f,c;
			to=e[it].v;
			f=e[it].c;
			c=e[it].cos;
			if(f<=0) continue;
			if(dis[to]>dis[now]+c){
				dis[to]=dis[now]+c;
				las[to]=it;
				flow[to]=min(flow[now],f);
				if(!inq[to]) q.push(to);
				inq[to]=1;
			}
		}
	}
	return dis[t]<INF;
}
void KM(){
	while(spfa()){
//		cout<<flow[t]<<' '<<dis[t]<<endl;
		maxflow+=flow[t];
		mincost+=dis[t]*flow[t];
		int now=t;
		while(now!=s){
			e[las[now]].c-=flow[t];
			e[las[now]^1].c+=flow[t];
			now=e[las[now]].u;
		}
	}
}
void make_edge(int U,int V,int C,int COS){
//	cout<<U<<' '<<V<<' '<<C<<' '<<COS<<endl;
	EDGE tmp;
	tmp.u=U;
	tmp.v=V;
	tmp.c=C;
	tmp.cos=COS;
	e.PB(tmp);
	each[U].PB(e.size()-1);
	swap(tmp.u,tmp.v);
	tmp.c=0;
	tmp.cos=-COS;
	e.PB(tmp);
	each[V].PB(e.size()-1);
}
int n,m;
int a[1001],b[1001];
signed main(){
	fastio;
	cin>>n>>m;
	rb(i,1,n) cin>>a[i];
	rb(i,1,n){
		b[i+1]+=a[i];
		b[i]-=a[i];
		make_edge(i,i+1,INF,0);
	}
	rb(i,1,m){
		int l,r,c;
		cin>>l>>r>>c;
		++r;
		make_edge(r,l,INF,c);
	}
	rb(i,1,n+1){
		if(b[i]>0){
			make_edge(s,i,b[i],0);
		}
		if(b[i]<0){
			make_edge(i,t,-b[i],0);
		}
	}
	KM();
	cout<<mincost<<endl;
	return 0;
}

标签:int,题解,dis,P3980,inq,GRAPH,NOI2008,SIZE,define
来源: https://www.cnblogs.com/gary-2005/p/14425438.html