【牛客网】安置路灯 C++
正确解法遍历路灯字符串,遇见“.”,就给计数器+1,然后往后挪三个位置。如果遇到“X”,就直接往后挪一个位置。#include<iostream>#include<string>using namespace std;int main() {int t, n;string s;cin >> t;for (int i = 0; i &...
·
正确解法
遍历路灯字符串,遇见“.”,就给计数器+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
点击阅读全文
更多推荐
活动日历
查看更多
直播时间 2025-02-26 16:00:00


直播时间 2025-01-08 16:30:00


直播时间 2024-12-11 16:30:00


直播时间 2024-11-27 16:30:00


直播时间 2024-11-21 16:30:00


目录
所有评论(0)