数字排列
标题:数字排列 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
小明负责公司年会,想出一个趣味游戏:
屏幕给出1~9中任意4个不重复的数字,大家以最快时间给出这几个数字可拼成的数字从小到大排列位于第N位置的数字,其中N为给出的数字中最大的(如果不到这么多个数字则给出最后一个即可)。
注意:
1)2可以当做5来使用,5也可以当做2来使用进行数字拼接,且屏幕不能同时给出2和5;
2)6可以当做9来使用,9也可以当做6来使用进行数字拼接,且屏幕不能同时给出6和9。
屏幕给出1~9中任意4个不重复的数字,大家以最快时间给出这几个数字可拼成的数字从小到大排列位于第N位置的数字,其中N为给出的数字中最大的(如果不到这么多个数字则给出最后一个即可)。
注意:
1)2可以当做5来使用,5也可以当做2来使用进行数字拼接,且屏幕不能同时给出2和5;
2)6可以当做9来使用,9也可以当做6来使用进行数字拼接,且屏幕不能同时给出6和9。
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; #define N 4 vector<int> readLine() { string line; cin >> line; size_t left = 0; size_t pos = 0; vector<int> arr; while ((pos = line.find(",", left)) != string::npos) { arr.push_back(stoi(line.substr(left, pos - left))); left = pos + 1; } if (left < line.size()) { arr.push_back(stoi(line.substr(left))); } sort(arr.begin(), arr.end()); return arr; } bool check(vector<int> d) { for (int i = 0; i < N; ++i) { if (d[i] < 1 || d[i] > 9) { return false; } } if (d[0] == d[1] || d[1] == d[2] || d[0] == d[2]) return false; auto cnt1 = 0; auto cnt2 = 0; for (int i = 0; i < N; ++i) { if (d[i] == 2 || d[i] == 5) cnt1 += 1; if (d[i] == 6 || d[i] == 9) cnt2 += 1; } if (cnt1 == 2 || cnt2 == 2) return false; return true; } int main() { auto data = readLine(); if (data.size() < 4) { cout << -1 << endl; return 0; } int midValue = data[3]; if (!check(data)) { cout << -1 << endl; } else { vector<int> result = { data[0], data[1], data[2], data[3] }; for (int i = 0; i < N; ++i) { if (data[i] == 2) { result.push_back(5); } if (data[i] == 5) { result.push_back(2); } if (data[i] == 6) { result.push_back(9); } if (data[i] == 9) { result.push_back(6); } } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if (data[i] == data[j]) continue; result.push_back(data[i] * 10 + data[j]); if (data[i] == 2) { result.push_back(5 * 10 + data[j]); } if (data[i] == 5) { result.push_back(2 * 10 + data[j]); } if (data[i] == 6) { result.push_back(9 * 10 + data[j]); } if (data[i] == 9) { result.push_back(6 * 10 + data[j]); } if (data[j] == 2) { result.push_back(data[i] * 10 + 5); } if (data[j] == 5) { result.push_back(data[i] * 10 + 2); } if (data[j] == 6) { result.push_back(data[i] * 10 + 9); } if (data[j] == 9) { result.push_back(data[i] * 10 + 6); } } } sort(result.begin(), result.end()); cout << result[midValue - 1] << endl; } return 0; }