破碎的项链USACO

Broken Necklace USACO

本文关键字:USACO 项链 破碎      更新时间:2023-10-16

USACO 问题在这个问题中定义-项链破损 USACO 问题。有人可以告诉我为什么我的代码在我的 PC 上正常工作,一直在 USACO 分级机中抛出分段错误?程序在 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;
}

让我们假设 n=1000point=999 ,所以 this 绕过了if(point==n)。但是,if g[point].color == 'w'执行时仍尝试访问第 n:th 值(未定义或有边界): checkcolor = g[point+1].color;