Panasonic Programming Contest 2020 C (Sqrt Inequality) 题解

General idea

Enter three integers aaa b b b c c c ifa + b <c \sqrt a + \sqrt b <\sqrt ca +b <c If established, output Yes, otherwise output No.

Sample

Enter #1

2 3 9

Output #1

No

2 + 3 < 9 \sqrt 2 + \sqrt 3 < \sqrt 9 2 +3 <9 invalid.

Input #2

2 3 10

Output #2

Yes

2 + 3 < 1 0 \sqrt 2 + \sqrt 3 < \sqrt 10 2 +3 <1 0 is established.

analysis

Wrong idea

First of all, due to sqrtthe floating-point precision error of the system function, the following code will obviously WA:

#include <cstdio>
#include <cmath>
using namespace std;

int main(int argc, char** argv)
{
    
    
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);
	double d = sqrt(double(a)) + sqrt(double(b));
	puts(d * d < c? "Yes": "No");
	return 0;
}

Therefore, this question must require special thinking ! ! !

Correct thinking

The following is the derivation process of the correct method:
a + b <c \sqrt a + \sqrt b <\sqrt ca +b <c
( a + b ) 2 < ( c ) 2 (\sqrt a + \sqrt b)^2 < (\sqrt c)^2 (a +b )2<(c )2
a + b + 2 a b < c a + b + 2\sqrt ab < c a+b+2a b<c
2 a b < c − a − b 2\sqrt ab < c - a - b 2a b<cab
( 2 a b ) 2 < ( c − a − b ) 2 (2\sqrt ab)^2 < (c - a - b)^2 (2a b)2<(cab)2
4 a b < ( c − a − b ) 2 4ab < (c - a - b)^2 4ab<(cab)2
Note: There is another case, that is,c − a − b <0 c-a-b <0cab<0 c < a + b c < a + b c<a+b , the answer should be yesNo. In this caseWA, themeeting is not considered, because(c − a − b) 2 (c-a-b)^2(cab)2 will "ignore negative numbers directly"!

Code

#include <cstdio>
using namespace std;

int main(int argc, char** argv)
{
    
    
	long long a, b, c;
	scanf("%lld%lld%lld", &a, &b, &c);
	long long d = c - a - b;
	if(d < 0) puts("No"); // 特殊情况c - a - b < 0直接输出No
	else puts((d * d > 4LL * a * b)? "Yes": "No");
	return 0;
}

AC screenshot

Guess you like

Origin blog.csdn.net/write_1m_lines/article/details/104897725