&& C++_USACO_Calf Flac

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
class small_pal{
private:
    int len;
    int pose;
public:
    small_pal(int len,int pose){
        this->len=len;
        this->pose=pose;
    }
    int getLen(){
        return len;
    }
    int getPose(){
        return pose;
    }
    void setLen(int len){
        this->len=len;
    }
    void setPose(int pose){
        this->pose=pose;
    }
};
bool isequal(char a,char b){
    if(a>='A' && a<='Z')
        a+=32;
    if(b>='A' && b<='Z')
        b+=32;
    if(a==b)
        return true;
    else
        return false;
}
int main(){
    ifstream fin("calfflac.in");
    ofstream fout("calfflac.out");
    string art_str="";
    vector<small_pal> pals;
    int i=0;
    int len=1;
    int pose=0;
    int forward=0;
    int back=0;
    int max_len=0;
    int max_pose=0;
    string max_str="";
    char ch=' ';
    fin>>ch;
    while(!fin.eof()){
        if((ch>='A' && ch<='Z')||(ch>='a' && ch<='z'))
            art_str.append(1,ch);
        fin>>ch;
    }
    fin.close();
    while(i<art_str.length()-2){
        if(isequal(art_str[i],art_str[i+1])){
            len++;
            i++;
            continue;
        }
        if(len==1){
            if(isequal(art_str[i],art_str[i+2])){
                small_pal pal(3,i);
                pals.push_back(pal);
            }
        }
        else{
            small_pal pal(len,i-len+1);
            pals.push_back(pal);
        }
        i++;
        len=1;
    }
    if(isequal(art_str[i],art_str[i+1])){
        small_pal pal(2,i);
        pals.push_back(pal);
    }
    for(int i=0;i<pals.size();i++){
        pose=pals[i].getPose();
        len=pals[i].getLen();
        forward=pose-1;
        back=pose+len;
        while(isequal(art_str[forward],art_str[back])){
            len+=2;
            pose--;
            forward=pose-1;
            back=pose+len;
            if(forward<0 || back>=art_str.size())
                break;
        }
        pals[i].setLen(len);
        pals[i].setPose(pose);
    }
    max_len=pals[0].getLen();
    for(int i=1;i<pals.size();i++){
        if(pals[i].getLen()>max_len){
            max_len=pals[i].getLen();
            max_pose=pals[i].getPose();
        }
    }
    max_str=art_str.substr(max_pose,max_len);
    fout<<max_len<<endl;
    fout<<max_str<<endl;
    return 0;
}

这个程序还有点儿问题,它输出的是纯字母。因为从一开始,我就只存了字母,其实可以都存,只是求最小回文串时,也要考虑其他符号的问题。但是我这两天一直有事情耽搁,没有集中精力,断断续续花了两天时间。我先做个记号,放在这里下次继续实现。

posted @ 2013-08-08 09:11  开心成长  阅读(249)  评论(0编辑  收藏  举报