• 18年春招某编程题:有三个整数X,Y,Z,要求进行若干次操作使得X,Y,Z相等


    题目描述:

    给定三个整数X,Y,Z,要求进行若干次操作使得X,Y,Z相等,操作有两种:

    1.从X,Y,Z中选择两个数都加1。

    2.从X,Y,Z中选择一个数加2。

    求最少需要多少次操作。

    题目思路:

    1.对X,Y,Z三个数进行排序,此处用的是降序排序。假设排序完之后X>Y>Z,如果Y-Z是奇数的话,那么对Z进行(Y - Z)/2次操作2的话,Z就会变成了Y-1了,即此时的Y=Y,Z=Y-1。那么此时只需先对Y,Z进行X-Y次操作1,使得X=X,Y=X,Z=X-1。然后再对X,Y进行1次操作1,最后再对Z进行一次操作2.最后X=Y=Z。这种情况下,共需要X - Y +(Y - Z)/2 + 2次操作。

    2.如果Y-Z是偶数的话,那么对Z进行(Y - Z)/2次操作2的话,Z就变成了Y了,即此时Y = Y,Z = Y。那么此时只需对Y,Z进行X - Y次操作1即可。这种情况下,共需要X - Y +(Y - Z)/2次操作。

    代码如下:

    #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;
    }
    int main()
    {
    
       int a[]={2,9,5};//测试用例
       Solution s;
       sort(a,a+3,cmp);
       cout<<s.minCount(a)<<endl;;
      
    }
    

      

  • 相关阅读:
    shell-条件测试
    51Nod 1279 扔盘子 (思维+模拟)
    51Nod 1042 数字0-9的数量(数位DP)
    Codeforces 1138B Circus (构造方程+暴力)
    51nod 1133 不重叠的线段 (贪心,序列上的区间问题)
    51nod 1091 线段的重叠(贪心)
    EOJ Monthly 2019.2 E 中位数 (二分+中位数+dag上dp)
    牛客练习赛39 C 流星雨 (概率dp)
    牛客练习赛39 B 选点(dfs序+LIS)
    Educational Codeforces Round 57
  • 原文地址:https://www.cnblogs.com/wangkundentisy/p/8888918.html
Copyright © 2020-2023  润新知