跳到正文

题解

题解:P1001 A+B Problem

LEWISAK约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年5月10日
收录
2026年5月27日
更新
2026年11月9日
篇幅
约 3 分钟
获赞
15
题目
P1001

版本

  1. v1当前

本篇题解并非本题的正规做法。

题解区还没有ISAP求最大流的方法?蒟蒻来一发!

注意到我们可以考虑将求解二数相加转化为求最大流问题,建出下图:

然后进行增广路求解,由于 1→t1\to t 和 2→t2 \to t 的流量都是无限的,所以最后最大流就是 s→1s \to 1 与 s→2s \to 2 的流量和,也就是 a+ba+b。

最后,实现上,由于 ISAP 无法处理负数,所以将 aa 和 bb 都加 10910^9 即可。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
namespace kong{bool st;}
namespace zhu{
int tot=1,head[1001000],lead[1001000],dep[1001000],gap[1001000],n,s,t,jia=1e9;
queue<int> q;
struct{
	int nxt,to,w;
}e[2002000];
void add(int u,int v,int w){
	e[++tot]={head[u],v,w};
	head[u]=tot;
	e[++tot]={head[v],u,0};
	head[v]=tot;
	return;
}
void bfs(){
	q.push(t);
	dep[t]=1;
	gap[1]++;
	while(!q.empty()){
		int x=q.front();
		q.pop();
		for(int i=head[x];i;i=e[i].nxt){
			int v=e[i].to;
			if(!dep[v]){
				dep[v]=dep[x]+1;
				q.push(v);
				gap[dep[v]]++;
			}
		}
	}
}
int dfs(int x,int flow){
	if(x==t||flow==0) return flow;
	int rest=flow;
	for(int i=lead[x];i&&rest;i=e[i].nxt){
		lead[x]=i;
		int v=e[i].to,w=e[i].w;
		if(dep[x]==dep[v]+1&&w>0){
			int t=dfs(v,min(rest,w));
			rest-=t;
			e[i].w-=t;
			e[i^1].w+=t;
		}
	}
	if(rest){
		gap[dep[x]]--;
		if(!gap[dep[x]]){
			dep[s]=n+1;
		}
		dep[x]++;
		gap[dep[x]]++;
	}
	return flow-rest;
}
int ISAP(){
	int ans=0;
	bfs();
	while(dep[s]<=n){
		for(int i=1;i<=n;i++){
			lead[i]=head[i];
		}
		ans+=dfs(s,1e18);
	}
	return ans;
}
string main(){
	int a,b;
	cin>>a>>b;
	a+=jia;b+=jia;
	s=3,t=4;
	add(s,1,a);add(s,2,b);
	add(1,t,a);add(2,t,b);
	n=4;
	cout<<ISAP()-jia*2<<'\n';
	return "调了好久……";
}
}
namespace kong{bool ed;double kj(){return (&st-&ed)/1048576.0;}}
signed main(){
	cerr<<zhu::main()<<'\n'<<kong::kj();
	return 0;
}