华为社招笔试
输入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; }
新战场:https://blog.csdn.net/Stephen___Qin