此问题中定义了USACO问题 - Broken Necklace USACO Problem。 有人可以告诉我为什么我的代码在我的PC上运行正常,在USACO Grader中不断抛出分段错误?程序在foreachsplit()函数内停止,直到完成才运行。
/*
ID: varun.b2
PROG: beads
LANG: C++11
*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct groups
{
int number;
char color;
}g[1000];
struct countcol
{
int count1;
int count2;
}c[1000];
int ccount;
void foreachsplit(groups g[1000], int n)
{
cerr<<"\nINSIDE FOREACHSPLIT";
int point = 0;
int i = 0;
ccount = 0;
int count1,count2,beg;
char checkcolor;
while(point<=n)
{
cerr<<"P:"<<point<<" ";
if(n==0)
{
c[ccount].count1 = g[0].number/2;
c[ccount++].count2 = 0;
break;
}
if(point==n)
break;
checkcolor = g[point].color;
count1 = 0;
count2 = 0;
if(checkcolor=='w')
{
checkcolor = g[point+1].color;
}
beg = point;
while(g[beg].color == checkcolor||g[beg].color=='w')
{
beg++;
count1+=g[beg].number;
}
checkcolor=g[beg].color;
while(g[beg].color == checkcolor||g[beg].color=='w')
{
beg++;
count2+=g[beg].number;
}
c[ccount].count1 = count1;
c[ccount++].count2 = count2;
point++;
}
cerr<<"\nWHILE LOOP HAS ENDED!";
}
int findmax()
{
cerr<<"\nINSIDE FINDMAX";
int temptotal,total;
total = c[0].count1 + c[0].count2;
for(int i=1;i<ccount;i++)
{
temptotal = c[i].count1 + c[i].count2;
if(total<temptotal)
total = temptotal;
}
cerr<<"\nTOTAL CALCULATED!";
return total;
}
int main()
{
cerr<<"INSIDE MAIN";
int N;
int count=0;
int i = 0,j=0;
string beads;
ifstream fin("beads.txt");
ofstream fout("beads.out");
fin>>N;
fin>>beads;
cerr<<"\nINPUT READ";
beads = beads + beads;
cerr<<"\nINPUT DUPLICATED";
char oricolor = beads[0];
g[0].number = 0;
for(i=0;i<beads.length();i++)
{
if(beads[i]==oricolor)
{
g[j].number++;
}
else
{
g[j].color = oricolor;
oricolor = beads[i];
g[++j].number = 1;
}
}
g[j].color = oricolor;
cerr<<"\nGROUPED INTO COLORS";
foreachsplit(g,j);
fout<<findmax()<<endl;
fin.close();
fout.close();
return 0;
}
答案 0 :(得分:0)
我们假设n=1000
和point=999
,因此这会绕过if(point==n)
。但是,if g[point].color == 'w'
执行时仍尝试访问第n个值(未定义或边界):
checkcolor = g[point+1].color;