在这里插入图片描述

正确解法

遍历路灯字符串,遇见“.”,就给计数器+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
在这里插入图片描述

点击阅读全文
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐