跳到正文

题解

题解:P1001 A+B Problem

justalearner约 4 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

线性规划好题。

题目要求我们算 A+BA+B,可以构造一个线性规划问题:

maximize⁡x1+x2s.t.{x1≤Ax2≤B\operatorname{maximize} x_1+x_2\\ s.t. \left\{ \begin{aligned} x_1\le A\\ x_2\le B \end{aligned} \right.

答案即为 A+BA+B。

当然这道题 AA 和 BB 可以是负的。所以可以给 AA 和 BB 分别加上一个 1×1091\times 10^9,最后答案减去 2×1092\times 10^9 即可。

线性规划具体实现方式参见 OI-wiki。

参考代码:

C++
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N=25;
const double eps=1e-8,INF=1e15;
inline int read(){
	char c=getchar();int x=0,f=1;
	while(c<'0'||c>'9'){if(c=='-')f=-1; c=getchar();}
	while(c>='0'&&c<='9'){x=x*10+c-'0'; c=getchar();}
	return x*f;
}
int n,m,type;
double a[N][N],ans[N];
int id[N<<1];
int q[N];
void Pivot(int l,int e){
	swap(id[n+l],id[e]);
	double t=a[l][e]; a[l][e]=1;
	for(int j=0;j<=n;j++) a[l][j]/=t;
	for(int i=0;i<=m;i++) if(i!=l && abs(a[i][e])>eps){
		t=a[i][e]; a[i][e]=0;
		for(int j=0;j<=n;j++) a[i][j]-=a[l][j]*t;
	}
}
bool init(){
	while(true){
		int e=0,l=0;
		for(int i=1;i<=m;i++) if(a[i][0]<-eps && (!l||(rand()&1))) l=i;
		if(!l) break;
		for(int j=1;j<=n;j++) if(a[l][j]<-eps && (!e||(rand()&1))) e=j;
		if(!e) {puts("Infeasible");return false;}
		Pivot(l,e);
	}
	return true;
}
bool simplex(){
	while(true){
		int l=0,e=0; double mn=INF;
		for(int j=1;j<=n;j++)
			if(a[0][j]>eps) {e=j;break;}
		if(!e) break;
		for(int i=1;i<=m;i++) if(a[i][e]>eps && a[i][0]/a[i][e]<mn)
			mn=a[i][0]/a[i][e],l=i;
		if(!l) {puts("Unbounded");return false;}
		Pivot(l,e);
	}
	return true;
}
int main(){
	srand(317);
	n=2,m=2;
	int A=read()+1E9,B=read()+1E9;
	a[0][1]=1,a[0][2]=1;
	a[1][0]=A,a[1][1]=1,a[1][2]=0;
	a[2][0]=B,a[2][1]=0,a[2][2]=1;
	for(int i=1;i<=n;i++) id[i]=i;
	if(init() && simplex()){
		printf("%.0lf\n",-a[0][0]-2E9);
	}
	else exit(-1);
}