A programming question in the spring of 2018: There are three integers X, Y, Z, and several operations are required to make X, Y, and Z equal

Topic description:

Given three integers X, Y, Z, several operations are required to make X, Y, and Z equal. There are two operations:

1. Select two numbers from X, Y, Z and add 1 to each.

2. Choose a number from X, Y, Z and add 2.

Find the minimum number of operations required.

Topic idea:

1. Sort the three numbers X, Y, Z, here is the descending sort. Assuming that X>Y>Z after sorting, if YZ is an odd number, then if (Y - Z)/2 operations 2 are performed on Z, Z will become Y-1, that is, Y=Y at this time , Z=Y-1. Then at this time, you only need to perform XY operations 1 on Y and Z first, so that X=X, Y=X, Z=X-1. Then perform one operation 1 on X, Y, and finally perform one operation on Z 2. Finally, X=Y=Z. In this case, a total of X - Y +(Y - Z)/2 + 2 operations are required.

2. If YZ is an even number, then (Y - Z)/2 operations are performed on Z, and Z becomes Y, that is, Y = Y, Z = Y at this time. Then at this time, you only need to perform X - Y operations 1 on Y and Z. In this case, a total of X - Y +(Y - Z)/2 operations are required.

code show as below:

#include<iostream>
#include<cassert>
#include<vector>
#include<stack>
#include<cstdio>
#include<unordered_map>
#include<queue>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;

class Solution {
public:
    int minCount(int a[])
    {
        int x = a[0],y = a[1],z = a[2];
        if((y - z) & 1)
        {
            return x - y + (y - z) / 2 +2;
        }
        else
        {
            return x - y + (y - z) / 2;
        }
    }


};
bool cmp(int  a,int b)
{
    return a > b;
}
intmain()
{

   int a[]={2,9,5};//Test case
   Solution s;
   sort(a,a+3,cmp);
   cout<<s.minCount(a)<<endl;;
  
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326216184&siteId=291194637