c++ - 我应该对我的 cpp 代码进行哪些更改才能获得正确的输出?
问题描述
//Question
/*一排有N个座位。给你一个长度为 N 的字符串 S;对于每个有效的 i,如果第 i 个座位是空的,则 S 的第 i 个字符为“0”,如果该座位上有人坐在,则为“1”。
如果两个人坐在彼此旁边,他们就是朋友。两个朋友总是属于同一群朋友。你能找到组的总数吗?
输入
输入的第一行包含一个整数 T,表示测试用例的数量。T 测试用例的描述如下。每个测试用例的第一行也是唯一一行包含一个字符串 S。
输出
对于每个测试用例,打印一行包含一个整数——组数。*/
// 我的代码
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin>>t;
int n=1e6;
for(int i=0;i<t;i++){
string g1;
cin>>g1;
int group;
group = 0;
for(int j=0;j<g1.length();j++){
if(g1[j] == '1'){
for(int h=1;h<n;h++){
if(g1[j+h] == '1'){
h++;
}else{
break;
}
group++;
}
} else{
continue;
}
}
cout<<group<<endl;
}
return 0;}
示例输入
4
000
010
101
01011011011110
示例输出
0 1 2 4
//我的输出
0
0
0
9
解决方案
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// you don't need n variable
// it is appropriate to use the length of the string instead
// it also will remove one warning for initialization
int n = 1e6;
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group; // you can use int group = 0; avoiding the statement below
group = 0;
// size_t stringLength = g1.length();
for (int j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++; // you need to add it here to starts counting
// better this way -> for (size_t h = 1; h < stringLength; h++)
for (int h = 1; h < n; h++) { // h < n && (j+h)<stringLength
if (g1[j + h] == '1') {
// you increasing h value twice - first in for statement, second here
// instead, you need to set j to j+h value
//h++;
// you just "moving" through the string till next'0'
j = j + h;
}
else {
break;
}
// this will increase group count for each next '1' in the string
// this is why you got 9 for the last string in your's example
//group++;
}
}
// this is not needed
//else {
// continue;
//}
}
cout << group << endl;
}
return 0;
}
推荐阅读
- tensorflow - 使用 tf 梯度更新 keras 模型
- google-cloud-endpoints - Google Cloud Endpoints:使用 protobuf.Any 字段对消息进行转码
- jenkins - GitHub 拉取请求 - 状态检查标题
- r - R:将函数应用于数据框列表中的数据框列(在 lapply 内应用)
- python - Python脚本在heroku上成功部署,但出现应用程序错误
- python - 捕获雨水:蛮力方法中的错误
- r - 使用 dplyr 和 paste0 汇总和整理结果后没有返回记录
- javascript - 猫鼬等待承诺错误
- python - 添加数组字段 OperationalError
- perl - 如何使用 Perl 根据它们的差异结果将目录中的文件排序到不同的文件夹中