首页 > 代码库 > Problem 006——Circular Sequence
Problem 006——Circular Sequence
Some DNA sequences exist in circular forms as in the following figure, which shows a circular sequence ``CGAGTCAGCT", that is, the last symbol ``T" in ``CGAGTCAGCT" is connected to the first symbol ``C". We always read a circular sequence in the clockwise direction.
Since it is not easy to store a circular sequence in a computer as it is, we decided to store it as a linear sequence. However, there can be many linear sequences that are obtained from a circular sequence by cutting any place of the circular sequence. Hence, we also decided to store the linear sequence that is lexicographically smallest among all linear sequences that can be obtained from a circular sequence.
Your task is to find the lexicographically smallest sequence from a given circular sequence. For the example in the figure, the lexicographically smallest sequence is ``AGCTCGAGTC". If there are two or more linear sequences that are lexicographically smallest, you are to find any one of them (in fact, they are the same).
Input
The input consists of T test cases. The number of test cases T is given on the first line of the input file. Each test case takes one line containing a circular sequence that is written as an arbitrary linear sequence. Since the circular sequences are DNA sequences, only four symbols, A, C, G and T, are allowed. Each sequence has length at least 2 and at most 100.
Output
Print exactly one line for each test case. The line is to contain the lexicographically smallest sequence for the test case.
The following shows sample input and output for two test cases.
Sample Input
2 CGAGTCAGCT CTCC
Sample Output
AGCTCGAGTC CCCT
CODE
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s[105],s1[105];
int N;
scanf("%d",&N);
while(N!=0)
{
scanf("%s",s);
int len=strlen(s);
strcpy(s1,s);
char s0[105];
strcat(s,s1);
strcpy(s0,s);
char ch[105];
int i,j;
for(i=0; i<len; i++)
{
int k=0;
for(j=i; j<len+i; j++)
{
ch[k]=s0[j];
k++;
}
int pd=strcmp(s1,ch);
if(pd>0)
strcpy(s1,ch);
memset(ch,0,len+5);
}
printf("%s\n",s1);
N--;
}
return 0;
}
MY WAY
其实对我来说,这个题耽搁了好久。因为一些其他原因没有及时做完。
每当想起这个题来总会有一些乱七八糟的事情发生,让我难以好好做题,从微博的时间上就可以看出来的。
这个题的思路还是比较简单的:
首先把输入的字符串复制一遍再接上,然后通过循环来依次找出最合适的字符串再输出。
这个题很好的运用了字符串函数,比如strlen,strcmp,strcpy,strcat……这些统统用到了,这真是一个有知识含量的题啊。呵呵。
Problem 006——Circular Sequence