【牛客网】安置路灯 C++
生活随笔
收集整理的這篇文章主要介紹了
【牛客网】安置路灯 C++
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正確解法
遍歷路燈字符串,遇見“.”,就給計數器+1,然后往后挪三個位置。如果遇到“X”,就直接往后挪一個位置。
#include<iostream> #include<string> using namespace std;int main() {int t, n;string s;cin >> t;for (int i = 0; i < t; i++) {cin >> n >> s;int sum = 0;int j = 0;while (j < n) {if (s[j] == '.') {sum++;j += 3;}else {j++;}}cout << sum << endl;}system("pause"); }錯誤解法
#include<iostream> using namespace std;int getBlackCount(char a, char b, char c) {int blackCount = 0;if (a == '.') {blackCount++;}if (b == '.') {blackCount++;}if (c == '.') {blackCount++;}return blackCount; }int main() {int t;// 測試用例數cin >> t;for (int i = 0; i < t; i++) {cout << "測試用例:" << i << endl;int n; cin >> n;cout << "總長度:" << n << endl;int totalBlack = 0;//需要照亮的區域總個數char a[1001] = { 0 };for (int j = 0; j < n; j++) {cin >> a[j];if (a[j] == '.') {totalBlack++;}}cout << "初始道路:" << a << endl;//計算路燈 貪心int total = 0;while (totalBlack > 0) {int maxBlackCount = 0;int index = -1;for (int k = 0; k < n - 2; k++) { // 找到照亮最多的位置int lightCount = getBlackCount(a[k], a[k + 1], a[k + 2]);if (lightCount > maxBlackCount) {maxBlackCount = lightCount;index = k;}}// 在此處照亮a[index] = 'X';a[index + 1] = 'X';a[index + 2] = 'X';// 總數減少totalBlack -= maxBlackCount;cout << "照亮后:" << a << endl;// 路燈加一total++;cout << "當前增加路燈數量:" << total << endl;}cout << "答案:" << total << "\n\n";cout << total << endl;}system("pause"); }錯誤原因
輸入:
1 6 .X....正確輸出:2
總結
以上是生活随笔為你收集整理的【牛客网】安置路灯 C++的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】忘记登录密码?遍历数字字
- 下一篇: 【牛客网】迷途的牛牛 C++