(1)描述:医学研究者最近发现了某些新病毒,通过对这些病毒的分析,得知它们的DNA序列都是环状的。现在研究者收集了大量的病毒DNA和人的DNA数据,想快速检测出这些人是否感染了相应的病毒。为方便研究,研究者将人的DNA和病毒的DNA均表示成由一些小写字母组成的字符串,然后检测某种病毒的DNA序列是否在患者的DNA序列中出现过,如果出现过,则此人感染了病毒,否则没有感染。注意:人的DNA序列是线性的,而病毒的DNA序列是环状的。
(2)输入:多组数据,每组数据有一行,为序列A和B,A对应病毒的DNA序列,B对应人的DNA序列。A和B都为“0”时输入结束。
(3)输出:对于每组数据输出一行,若患者感染了病毒输出“YES”,否则输出“NO”。
思路:
先写一个BF算法作为匹配字符串的函数
对于循环的字符串,只需要另外写一个分解字符串的方法,把每一种情况的字符串都放入BF算法中与人类DNA字符串进行匹配,最后在main函数中判断结果。
源代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char x[20];
char y[50];
}dna;
typedef struct
{
dna arr[20];
}list;
int test(char x[],char y[]) //BF算法
{
int flag;
int i=0,j=0;
int lenx=strlen(x);
int leny=strlen(y);
while(i<lenx&&j<leny)
{
if(x[i]==y[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
}
if(j>=leny) return 1;
else return 0;
}
int divide(char x[],char y[],int k) //分解字符串为循环子串
{
char str[100];
int len=strlen(x);
int i=k;
int pos=0;
int count=0;
int flag=0;
while(true)
{
if(i>len-1)
{
i=0;
}
str[pos]=x[i];
i++;
pos++;
count++;
if(count==len)
{
flag=1;
break;
}
}
//t printf("%s\n",str);
if(flag) return test(y,str);
else return 0;
}
int main()
{
list l;
int i=0;
while(true)
{
// printf("请依次输入病毒DNA序列,人DNA序列:\n");
scanf("%s %s",l.arr[i].x,l.arr[i].y);
if(strcmp(l.arr[i].x,"0")==0&&strcmp(l.arr[i].y,"0")==0)
break;
i++;
}
int count1=1;
int count2=1;
int temp=0;
for(int index=0;index<i;index++)
{
int len_x=strlen(l.arr[index].x);
// printf("%d\n",len_x);
if(count1<len_x)
{
for(int k=1;k<=len_x-1;k++)
{
temp=divide(l.arr[index].x,l.arr[index].y,count2);
// printf("%d\n",temp);
count2++;
}
// printf("test:%d \n",test(l.arr[index].x,l.arr[index].y));
if(test(l.arr[index].y,l.arr[index].x)||temp)
printf("YES\n");
else
printf("NO\n");
}
count1=1;
count2=1;
}
return 0;
}