9.20 思科笔试 编程题C++
直接模拟,第一遍只过了90%,发现是没考虑m=0的情况,加上就全部通过了
#include<iostream> #include<vector> using namespace std; int find_max(vector<int>& a, vector<int>& visited) { int max_index = -1; int tmp = -100; for (int i = 0; i < a.size(); i++) { if (visited[i] > 0)continue; if (a[i] > tmp) { tmp = a[i]; max_index = i; } } return max_index; } int main() { int n, m; cin >> n >> m; int x; vector<int>a; for (int i = 0; i < n; i++) { cin >> x; a.push_back(x); } vector<int>visited(n, 0); //0-未选,1-被A选,2-被B选 int count = 0; int k = find_max(a, visited); //找到最大元素的下标 while (k != -1) { //A选 visited[k] = 1; //向左右搜索(m=0时不必要) if (m > 0) { //向左搜索 count = 0; for (int i = k; i >= 0; i--) { if (visited[i] == 0) { count++; visited[i] = 1; if (count == m)break; } } //向右搜索 count = 0; for (int i = k; i < a.size(); i++) { if (visited[i] == 0) { count++; visited[i] = 1; if (count == m)break; } } } //B选 k = find_max(a, visited); if (k == -1)break; visited[k] = 2; if (m > 0) { count = 0; for (int i = k; i >= 0; i--) { if (visited[i] == 0) { count++; visited[i] = 2; if (count == m)break; } } count = 0; for (int i = k; i < a.size(); i++) { if (visited[i] == 0) { count++; visited[i] = 2; if (count == m)break; } } } k = find_max(a, visited); //继续轮到A } for (int i = 0; i < n; i++) { if (visited[i] == 1)cout << 'A'; if (visited[i] == 2)cout << 'B'; } cout << endl; return 0; }