loj2031 「SDOI2016」数字配对

跑最大费用最大流,注意到每次 spfa 出来的 cost 一定是越来越少的,啥时小于 (0) 了就停了吧。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long ll;
int n, a[205], b[205], c[205], dd[205], hea[205], cnt, ss, tt, pre[205];
const int oo=0x3f3f3f3f;
bool vis[205];
ll dis[205], ans;
queue<int> d;
struct Edge{
	int too, nxt, val;
	ll cst;
}edge[200005];
int calc(int x){
	int re=0;
	for(int i=2; i*i<=x; i++)
		if(x%i==0){
			while(x%i==0){
				x /= i;
				re++;
			}
		}
	if(x!=1)	re++;
	return re;
}
void add_edge(int fro, int too, int val, ll 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, ll 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);
	dis[ss] = 0;
	vis[ss] = true;
	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]!=0x3f3f3f3f3f3f3f3f;
}
void mcmf(){
	ll cost=0;
	while(spfa()){		int tmp=oo;
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
			tmp = min(tmp, edge[i].val);
		if(cost+(ll)tmp*dis[tt]<=0){
			cost += (ll)tmp * dis[tt];
			ans += tmp;
			for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
				edge[i].val -= tmp;
				edge[i^1].val += tmp;
			}
		}
		else{
			ans += cost / (-dis[tt]);
			return ;
		}
	}
}
int main(){
	memset(hea, -1, sizeof(hea));
	cin>>n;
	for(int i=1; i<=n; i++)	scanf("%d", &a[i]);
	for(int i=1; i<=n; i++)	scanf("%d", &b[i]);
	for(int i=1; i<=n; i++)	scanf("%d", &c[i]);
	for(int i=1; i<=n; i++)	dd[i] = calc(a[i]);
	ss = 0; tt = n + 1;
	for(int i=1; i<=n; i++){
		if(dd[i]&1){
			addEdge(ss, i, b[i], 0);
			for(int j=1; j<=n; j++)
				if(a[j]%a[i]==0 && dd[j]==dd[i]+1)	addEdge(i, j, oo, (ll)-c[i]*c[j]);
				else if(a[i]%a[j]==0 && dd[i]==dd[j]+1)	addEdge(i, j, oo, (ll)-c[i]*c[j]);
		}
		else	addEdge(i, tt, b[i], 0);
	}
	mcmf();
	printf("%lld
", ans);
	return 0;
}
原文地址:https://www.cnblogs.com/poorpool/p/8888422.html