串——病毒检测:BF检测

 

 

#include<iostream>
#include <cstring>
#include <fstream>

using namespace std;

#define MAXLEN 20

/*
 病毒检测,BF算法,匹配子串
*/

typedef struct{
    char ch[MAXLEN+1];
    int length;
}SString;

string StrAssign(SString &S,string e){
    strcpy(S.ch,e.c_str());
    S.length = e.length();
    for(int i=S.length;i>0;i--){
        S.ch[i] = S.ch[i-1];
    }
    return "OK";
}


int Index_BF(SString S,SString T){             //返回匹配成功的开始位置
    int i,j ;
    i = j = 1;
    while(i <= S.length && j <= T.length ){
        if( S.ch[i] == T.ch[j] ) {++i;++j;}
        else
        {
            i = i-j+2;j=1;
        }
    }
    if(j > T.length) return i-T.length;
    else return 0;

}

int main(){

    ifstream inFile("Input.txt");
    ofstream outFile("Output.txt");

    SString Virus;
    SString Person;
    SString temp;

    char Vir[] = {' '};
    int flag = 0;
    int m;

    int num;
    inFile >> num;

    while(num--){
        //inFile >> Virus.ch+1;
        string V;
        string P;

        inFile >> V;
        strcpy(Virus.ch+1,V.c_str());
        Virus.length = V.length();     //接收文件中的病毒DNA
        temp.length = V.length();      //初始化Virus和temp

        inFile >> P;
        strcpy(Person.ch+1,P.c_str()); //接收文件中的病人DNA
        Person.length = P.length();

    
        outFile << Virus.ch+1 <<"   "; //例子是通过Vir.ch来存储Virus.ch,然后在最后一起输出,因为
                                       //赋值需要用到strcpy函数,就会让Vir.ch的地址与Virus.ch的地址
                                       //联系在一起,Virus.ch变了,Vir.ch也会跟着变,所以提起输出

        flag = 0;
        m = V.length();

        for(int i = m+1,j=1;j<m;j++)
            Virus.ch[i++] = Virus.ch[j];          //将病毒DNA扩大1倍

        //Virus.ch[2*m+1] = '\0';                   //结束符号

        for(int i=0;i<m;i++){

            for(int j=1;j<=m;j++) temp.ch[j] = Virus.ch[i+j];    //病毒DNA为环状,轮流由第i个字母做开头

        //temp.ch[m+1] = '\0';
        cout << Person.ch+1<<"  "<<temp.ch+1<<endl;
        flag = Index_BF(Person,temp);
        cout << flag<<endl;
        if(flag) break;
        }

        
        // cout << "Virus[2] is : "<< Virus.ch[2];
        if(flag) outFile <<Person.ch+1 << " "<<"YES"<<endl;
        else outFile <<Person.ch+1 << " "<<"No"<<endl;
    }


    system("pause");
    return 0;
}

 

posted @ 2020-11-21 20:18  倔强的不死人  阅读(372)  评论(0编辑  收藏  举报