我在USACO上解决了一个问题,分级员给了我以下错误:
运行1:执行错误:您的程序出现此运行时错误: 非法文件打开(/ dev / tty)。该程序运行0.003 CPU 错误前几秒。它使用了2164 KB的内存。
根据USACO帮助页面,错误与越界数组索引有关。我用几个测试用例成功测试了我的代码,并且我一直小心边界和数组索引,但不幸的是我找不到错误。有什么建议吗?
#include <stdio.h>
#include <string.h>
int main(){
int i, flag, flag2, lcount, rcount, gcount, nbeads, start;
char right, left, necklace[800];
FILE *fin = fopen ("beads.in", "r");
FILE *fout = fopen ("beads.out", "w");
fscanf(fin, "%d %s", &nbeads, necklace);
strcat(necklace,necklace);
necklace[2*nbeads] = '\0';
flag = 1;
left = right = ' ';
start = gcount = 0;
// First cut
for(i = start, lcount = 0; necklace[i] != right && i < nbeads; i++, lcount++)
if((flag) && (necklace[i] != 'w')){
left = necklace[i];
right = (left == 'b') ? 'r' : 'b';
flag--;
}
gcount = lcount;
if(i < nbeads){
// Remaining cuts
flag = 2;
flag2 = 0;
for(start = i; start > 0 && necklace[start - 1] == 'w'; start--, lcount--);
while(flag){
for(i = start, rcount = 0; necklace[i] != left && i < 2*nbeads; i++, rcount++);
gcount = (gcount < lcount + rcount) ? lcount + rcount : gcount;
lcount = rcount;
right = (right == 'b') ? 'r' : 'b';
left = (left == 'b') ? 'r' : 'b';
for(start = i; start > 0 && necklace[start - 1] == 'w'; start--, lcount--);
if(!flag2 && start >= nbeads){
gcount -= (i - nbeads);
break;
}
flag2++;
if(start >= nbeads) flag--;
}
}
fprintf(fout, "%d", gcount);
fclose(fin);
fclose(fout);
return 0;
}