Same Integers

版权声明: https://blog.csdn.net/qq_40829288/article/details/80621897

Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

You are given three integers AB and C. Find the minimum number of operations required to make AB and C all equal by repeatedly performing the following two kinds of operations in any order:

  • Choose two among AB and C, then increase both by 1.
  • Choose one among AB and C, then increase it by 2.

It can be proved that we can always make AB and C all equal by repeatedly performing these operations.

Constraints

  • 0A,B,C50
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make AB and C all equal.


Sample Input 1

Copy
2 5 4

Sample Output 1

Copy
2

We can make AB and C all equal by the following operations:

  • Increase A and C by 1. Now, ABC are 355, respectively.
  • Increase A by 2. Now, ABC are 555, respectively.

Sample Input 2

Copy
2 6 3

Sample Output 2

Copy
5

Sample Input 3

Copy
31 41 5

Sample Output 3

Copy
23

题意:给你三个数,你可以选择其中两个数把它们分别加1,也可以选择其中一个数把它加2。经过一系列变化使它们相等,并输出经过的次数。

思路:可以用一个数组做,用sort函数使它们从小到大排序,保证a[0]<=a[1]<=a[2];

有三种情况:

1.a[0]<a[1]=a[2],a[0]+2;    

2.a[0]=a[1]<a[2],a[0]+1,a[1]+1;    

3.a[0]<a[1]<a[2],a[0]+2;

用if作条件判断,step记录变换次数就行。

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[3];
	int step;
	while(cin>>a[0]>>a[1]>>a[2])
	{
		step=0;
		while(a[0]!=a[1]||a[1]!=a[2])
		{
			if(a[0]==a[1])
			{
				a[0]+=1;
				a[1]+=1;
				step++;
			}
			else if(a[1]==a[2])
			{
				a[0]+=2;
				step++;
			}
			else
			{
				a[0]+=2;
				step++;
			}
			sort(a,a+3);
		}
		cout<<step<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40829288/article/details/80621897