使用KMP算法来完成病毒感染检测的方案。

(1) 输入说明:多组数据,每组数据有1行,为序列A和序列BA对应病毒序列,B对应人的DNA序列,AB都为“0”时输入结束。

(2) 输出说明:对于每组数据输出1行,若患者感染了病毒则输出“YES”,否则输出“NO”。

(3) 测试用例:

输入样例:

abbab  abbabaab

baa  cacdvcabacsd

abc def

0 0

输出样例:

YES

YES

NO

代码:

#include<iostream>
#include<cstring>

#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 255

using namespace std;

typedef struct{
    char ch[MAXSIZE+1];//0号位置不放字符 
    int length;
}SString;

int Index(SString s, SString t, int pos)
{//返回t在主串s中第pos个字符开始第一次出现的位置,如果找不到,则返回值为0 
    int i = pos, j = 1;
    //cout << "s.length" << s.length << endl;
    //cout << "t.length" << t.length << endl;
    while(i<=s.length && j<=t.length)
    {    
        //cout << j << endl;
        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;
    }
}

void Virus_detection()
{
    SString people, virus, temp;
    int flag, len;
    cin >> virus.ch+1;
    virus.length = strlen(virus.ch) - 1;
    cin >> people.ch+1;
    people.length = strlen(people.ch+1);
    while(virus.ch[1]!='0' && people.ch[1]!='0')
    {
        flag = 0;
        len = virus.length;
        for(int i=len+1,j=1;j<=len;j++)
            virus.ch[i++] = virus.ch[j];//将virus复制,变成原来的两倍
        virus.ch[2*len + 1] = '\0';
        
        for(int i=0;i<len;i++)
        {
            for(int j=1;j<=len;j++)
                temp.ch[j] = virus.ch[i+j];
            temp.ch[len + 1] = '\0';
            temp.length = strlen(temp.ch) - 1;
            flag = Index(people, temp, 1);
            if(flag)
                break;
        }
        
        if(flag)
            cout << "YES" << endl;
        else
            cout << "NO" << endl; 

        cin >> virus.ch+1;
        virus.length = strlen(virus.ch) - 1;
        cin >> people.ch+1;
        people.length = strlen(people.ch+1);
    }
}

int main()
{
    Virus_detection();
    
    return 0;
}

分析:

一开始一直结果一直不对,调试了很久,发现是  people.length = strlen(people.ch) - 1 的问题,就改成了  people.length = strlen(people.ch+1)  然后才对,但是PTA版本不会有这个问题,猜测应该是编译器的问题。

猜你喜欢

转载自www.cnblogs.com/minsiL/p/12901639.html
今日推荐