1.判断字符串是否有效,暴力可A
#include <iostream> #include<string> using namespace std; int main() { int n; cin >> n; int cnt = 0; for (int i = 0; i < n; i++) { string str; cin >> str; if (str.size() >= 1 && str.size() <= 10) { int sz = str.size(); int j = 0; for (; j < sz; j++) { int ch = (int)str[j]; if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { continue; } else { break; } } if (j == sz) { cnt++; } } } cout << cnt; return 0; }2.数字排列的排列变换问题,暴力的话会超时,需要简化任务,例如,如果遇到连续的偶数个操作2,就可以把这些连续的操作2消掉;如果遇到连续的4个操作1,也可以把这些操作1消掉;
#include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> nums(n); for (int i = 1; i <= n; i++) { nums[i - 1] = i; } vector<int> datas; for (int i = 0; i < m; i++) { int tmp; cin >> tmp; datas.push_back(tmp); } vector<int> tasks; int cnt1 = 0; int cnt2 = 0; int last = -1; for (int i = 0; i < m; i++) { int now = datas[i]; if (now == last && last == 2) { cnt2++; if (i == m - 1) { if (cnt2 % 2) { tasks.push_back(2); } } } else if (now == last && last == 1) { cnt1++; if (i == m - 1) { cnt1 %= 4; for (int j = 0; j < cnt1; j++) { tasks.push_back(1); } } } else if (now != last) { if (now == 1) { if (cnt2 % 2) { tasks.push_back(2); } cnt2 = 0; cnt1 = 1; if (i == m - 1) { tasks.push_back(1); } } else { cnt1 %= 4; for (int j = 0; j < cnt1; j++) { tasks.push_back(1); } cnt2 = 1; cnt1 = 0; if (i == m - 1) { tasks.push_back(2); } } } last = now; } int sz = tasks.size(); for (int i = 0; i < sz; i++) { int tmp = tasks[i]; if (tmp == 1) { int first = nums[0]; for (int i = 1; i < n; i++) { nums[i - 1] = nums[i]; } nums[n - 1] = first; } else { for (int j = 0; j < n; j += 2) { swap(nums[j], nums[j + 1]); } } } for (int i = 0; i < n; i++) { cout << nums[i] << " "; } return 0; }
全部评论
(3) 回帖