C++ 为什么我在codechef的CMPRSS问题中得到WA(错误答案)?
我在CodeChef的压缩列表问题CodeCMPRSS中得到了错误的答案,以下是问题的链接: 我已经检查了问题中给出的示例输出,以及一些自制的测试用例,它工作正常。我没有发现代码中有什么错误 我的做法如下:C++ 为什么我在codechef的CMPRSS问题中得到WA(错误答案)?,c++,C++,我在CodeChef的压缩列表问题CodeCMPRSS中得到了错误的答案,以下是问题的链接: 我已经检查了问题中给出的示例输出,以及一些自制的测试用例,它工作正常。我没有发现代码中有什么错误 我的做法如下: #include <bits/stdc++.h> using namespace std; vector<int> number; int main() { int t; cin>>t; while(t--){
#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;
}
您忘记检查零件中是否存在编号[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++;
}
您的逻辑部分正确,因为您忘记检查向量的上限索引:请检查粗体字母或**代码**之间缺少的代码: 包括 使用名称空间std 向量数; 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;
}
查看my。对于不熟悉佤邦的人,它是美国华盛顿州的缩写。或者它可能代表错误的答案。这就是我喜欢缩写的原因,这里有一个多对一的关系{,你可以有一个越界访问,因为你没有测试那个C++的No.1a好奇,你使用的C++引用包括什么?你的程序将更有效地编译包含和包含。你知道什么是BITS/STDC++H?里面有很多你不需要的东西。ic包含文件。