欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

华为社招笔试

程序员文章站 2022-06-04 16:54:16
...

输入10个整数,从中选出3个,使得x^2+xy-y^2+z的值最小.

例子:

输入: 1 3 1 1 1 1 1 1 1 1 

输出:-4

//最初版本:比较傻的版本.

#include<iostream>
#include<vector>#include<algorithm>
using namespace std;

int main()
{
    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;
    while (cin >> a1 >> a2 >> a3 >> a4 >> a5 >> a6 >> a7 >> a8 >> a9 >> a10)
    {
        int arr[10] = { a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 };
        vector<int> vecInt(arr, arr+10);
        vector<int> vecRes;
        for (int i = 0; i < vecInt.size(); i++)
        {
            for (int j = 0; j < vecInt.size(); j++)
            {
                for (size_t k = 0; k < vecInt.size(); k++)
                {
                    if (i != j && j != k && k != i)
                    {
                        int x = vecInt[i];
                        int y = vecInt[j];
                        int z = vecInt[k];
                        int result = x*x+x*y-y*y+z;
                        vecRes.push_back(result);
                    }
                    else
                    {
                    }
                }
            }
        }
        sort(vecRes.begin(), vecRes.end());
        cout << vecRes[0];
    }

    return 0;
}

//对输入进行优化

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
    int num;
    vector<int> vecInt;
    while (cin >>num)    //如果一行输入多个数,windows下Ctrl+Z会终止输入.
    {
        vecInt.push_back(num);
    }
    vector<int> vecRes;
    for (int i = 0; i < vecInt.size(); i++)
    {
        for (int j = 0; j < vecInt.size(); j++)
        {
            for (size_t k = 0; k < vecInt.size(); k++)
            {
                if (i != j && j != k && k != i)
                {
                    int x = vecInt[i];
                    int y = vecInt[j];
                    int z = vecInt[k];
                    int result = x*x + x*y - y*y + z;
                    vecRes.push_back(result);
                }
                else
                {
                }
            }
        }
    }
    sort(vecRes.begin(), vecRes.end());
    cout << vecRes[0];
    return 0;
}