[One Question of the Day] Counting Candies

Source of the topic
Niuke.com
Link: Calculating Candy

The title describes the
three people A, B, and C are good friends. Everyone has some candies in their hands. We don’t know how many candies each of them has in their hands, but we know the following information:
A-B, B-C , A + B, B + C. These four numbers. Each letter represents the number of candies owned by each person. Now we need to use these four values ​​to calculate how many candies each person has, namely A, B, C. It is guaranteed that at most only one set of integers A, B, and C satisfy all the conditions of the question.

Enter a description:

The input is a line, a total of 4 integers, respectively A-B, B-C, A + B, B + C, separated by spaces. The range is between -30 and 30 (closed interval).

Output description:

The output is a line. If there are integers A, B, and C that meet the requirements, A, B, and C will be output in order, separated by spaces, and no spaces at the end of the line. If there is no such integer A, B, C, output No

enter:

1 -2 3 4

Output:

2 1 3

The idea of ​​solving the problem
is actually a system of ternary linear equations that we learned in elementary school. Let the input numbers be a, b, c, d in order; then A=(a+c)/2,C=(db)/2 , B has two solutions, B1=(ca)/2, B2=(b+d)/2, if B1 and B2 are not equal, there is no solution.

Code display

#include <iostream>
using namespace std;

int main()
{
    
    
	int a,b,c,d;
	cin >> a >> b >> c >> d;
	int A = (a+c)/2;
	int C = (d-b)/2;
	int B1 = (c-a)/2;
	int B2 = (b+d)/2;
	if(B1 != B2)
		cout << "No";
	else
		cout << A << " " << B1 << " " << C;
	return 0;
}

Guess you like

Origin blog.csdn.net/zhao_leilei/article/details/110290075
Recommended