为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?

Why I'm getting WA(Wrong Answer) in CMPRSS problem of codechef?

本文关键字:WA 错误 答案 问题 代码 CMPRSS 为什么      更新时间:2023-10-16

我在CodeChef的"压缩列表"问题代码(CMPRSS(中得到WA(错误答案(,这是问题的链接:https://www.codechef.com/problems/CMPRSS我已经检查了问题中给出的示例输出以及一些自制的测试用例,并且它工作正常。我没有发现我的代码中出了什么问题

这是我的方法:

#include <bits/stdc++.h>
using namespace std;
vector<int> number;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=0;i<n;i++){
int temp;
cin>>temp;
number.push_back(temp);
}
int i;
for(i=0;i<n-1;i++){
int count = 0;
int temp = i;
while (number[temp+1]-number[temp]==1){
temp++;
count++;
}
if(count>1){
if(i+count==n-1){
cout<<number[i]<<"..."<<number[i+count]<<"n";
} else{
cout<<number[i]<<"..."<<number[i+count]<<",";
}
i = i + count;
}
else{
cout<<number[i]<<",";
}
}
if(i!=n){
cout<<number[n-1]<<"n";
}
number.clear();
}

return 0;
}

您忘记检查零件中是否存在number[temp+1]

while (number[temp+1]-number[temp]==1){
temp++;
count++;
}

因此,它可能会读取数组之外并产生错误的输出.
请尝试这种情况:

2
5
1 2 3 4 5
3
1 2 3

部分应该是这样的:

while (temp+1 < static_cast<int>(number.size()) && number[temp+1]-number[temp]==1){
temp++;
count++;
}

你的逻辑部分正确,因为你忘了检查向量的上限索引: 请检查粗体字母中或代码之间缺少的代码:

#include 使用命名空间标准;

向量数; int main(( {

int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=0;i<n;i++){
int temp;
cin>>temp;
number.push_back(temp);
}
int i;
for(i=0;i<n-1;i++){
int count = 0;
int temp = i;
while (**temp+1<n &&** number[temp+1]-number[temp]==1){
temp++;
count++;
}
if(count>1){
if(i+count==n-1){
cout<<number[i]<<"..."<<number[i+count]<<"n";
} else{
cout<<number[i]<<"..."<<number[i+count]<<",";
}
i = i + count;
}
else{
cout<<number[i]<<",";
}
}
if(i!=n){
cout<<number[n-1]<<"n";
}
number.clear();
}

return 0;

}

检查我的解决方案。