其他分享
首页 > 其他分享> > 【洛谷P5331】【SNOI2019】—通信(最小费用最大流+主席树优化建边)

【洛谷P5331】【SNOI2019】—通信(最小费用最大流+主席树优化建边)

作者:互联网

传送门


洛谷垃圾数据
写暴力,不开longlonglonglonglonglong都能过

由于n1000n\le1000n≤1000
所以能很简单的想到n2n^2n2建边的费用流
洛谷数据只需要在建边的时候判一下valwval\le wval≤w就可以过

考虑把绝对值拆开
对2种情况分别以权值为下标建主席树建边即可

#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
    static char ibuf[RLEN],*ib,*ob;
    (ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ob==ib)?EOF:*ib++;
}
inline int read(){
    char ch=gc();
    int res=0,f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
#define ll long long
#define re register
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
#define poly vector<int>
#define chemx(a,b) ((a)<(b)?(a)=(b):0)
#define chemn(a,b) ((a)>(b)?(a)=(b):0)
cs int N=2205,M=N*N;
int n,w,str,des,a[N],pw,mncost;
int tp[N],adj[N],nxt[M<<1],to[M<<1],cost[M<<1],cap[M<<1],cnt=1;
inline void addedge(int u,int v,int w,int c){
	nxt[++cnt]=adj[u],adj[u]=cnt,to[cnt]=v,cap[cnt]=w,cost[cnt]=c;
	nxt[++cnt]=adj[v],adj[v]=cnt,to[cnt]=u,cap[cnt]=0,cost[cnt]=-c;
}
int dis[N],vis[N];
queue<int> q;
inline bool spfa(){
	memset(vis,0,sizeof(vis));
	memset(dis,127/3,sizeof(dis));
	dis[str]=0,vis[str]=1,q.push(str);
	while(!q.empty()){
		int u=q.front();q.pop();
		vis[u]=0;
		for(int e=adj[u];e;e=nxt[e]){
			int v=to[e];
			if(dis[v]>dis[u]+cost[e]&&cap[e]>0){
				dis[v]=dis[u]+cost[e];
				if(!vis[v])q.push(v),vis[v]=1;
			}
		}
	}
	return dis[des]!=dis[0];
}
int dfs(int u,int flow){
	if(u==des)return flow;
	vis[u]=1;
	int res=0;
	for(int &e=tp[u];e;e=nxt[e]){
		int v=to[e];
		if(!vis[v]&&cap[e]>0&&(dis[v]==dis[u]+cost[e])){
			int now=dfs(v,min(flow-res,cap[e]));
			res+=now,cap[e]-=now,cap[e^1]+=now,mncost+=now*cost[e];
			if(res==flow)break;
		}
	}
	return res;
}
inline void mfmc(){
	while(spfa()){
		memset(vis,0,sizeof(vis));
		memcpy(tp,adj,sizeof(adj));
		dfs(str,1e9);
	}
}
int main(){
	#ifdef Stargazer
	freopen("lx.cpp","r",stdin);
	#endif
	n=read(),w=read();
	for(int i=1;i<=n;i++)a[i]=read();
	str=2*n+1,des=str+1,pw=des+1;
	for(int i=1;i<=n;i++)addedge(str,i,1,0),addedge(n+i,des,1,0);
	addedge(pw,des,1e9,w);
	for(int i=1;i<=n;i++){
		addedge(i,pw,1,0);
		for(int j=1;j<i;j++)if(abs(a[i]-a[j])<=w)
		addedge(i,j+n,1,abs(a[i]-a[j]));
	}
	mfmc();
	cout<<mncost<<'\n';
}

标签:P5331,now,洛谷,int,res,vis,建边,define,dis
来源: https://blog.csdn.net/qq_42555009/article/details/101228173