跳到正文

闲话

B2001 题解

tuntunQwQ约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月29日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前

题目大意:给定两个整数 a,ba,b ,请求出 a+ba+b 的值。

前置芝士——豚鼠定理

我们可以用豚鼠定理将其简化为:对于给定的 a,ba,b,求 a×a+2×a×b+b×b−a×a−2×a×b+b×b2+(max⁡(a,b)or⁡0)\frac{\sqrt{a\times a+2\times a\times b+b\times b}-\sqrt{a\times a-2\times a\times b+b\times b}}{2}+(\max(a,b)\operatorname{or}0) 的值。

因为 a,b≤4×1018a,b\le 4\times 10^{18},乘在一起会爆long long,所以我们用__int128来存。对于sqrt运算,可以用二分实现,注意左右边界的初值。

cpp代码:

C++
#include<bits/stdc++.h>
using namespace std;
__int128 read(){
	__int128 x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*f;
}
void write(__int128 x){
	if(x<0){
		putchar('-');
		x=-x;
	}
	if(x>9) write(x/10);
	putchar(x%10^48);
}
__int128 sqr1(__int128 x){
	return x*x;
}
__int128 times(__int128 x,__int128 y){
	__int128 z=2;
	return x*y*z;
}
__int128 sqrt1(__int128 x){
	unsigned __int128 l=0,r=1e19,ans=1;
	while(l<=r){
		unsigned __int128 mid=(l+r)/2;
		if(mid*mid>x){
			r=mid-1;
		}else{
			l=mid+1;
			ans=mid;
		}
	}
	return ans;
}
int main(){
	__int128 a=read(),b=read(),t;
	t=max(a,b);
	write((t|0)+(__int128)( sqrt1(sqr1(a)+times(a,b)+sqr1(b))-sqrt1(sqr1(a)-times(a,b)+sqr1(b)) )/2 );
	return 0;
}
原文