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, ACG 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

长度为n的环状串有n种表示法,分别为从某个位置开始顺时针得到。例如,如图的环状串有10种表示:CGAGTCAGCT,GAGTCAGCTC,AGTCAGCTCG等。在这些表示法中,字典序最小的称为“最小
表示”。(字典序:就是字符串在字典中的序列。一般地,对于两个字符串,从第一个字符开始比较,当某一个位置的字符不同时,该位置字符较小的串,字典序较小,如abc比bcd小;如果其中一个字符
串已经没有更多字符,但另一个字符串还没有结束,则较短的字符串的字典序较小,如hi比history小。)

输入一个长度为n(n<=100)的环状DNA串(只包含A、C、G、T这4种字符)的一种表示法,你的任务是输出该环状串的最小表示。例如,CTCC的最小表示是CCCT,CGAGTCAGCT的最小表示为
AGCTCGAGTC。
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define maxn 105
 4 int less(const char*s,int p,int q)
 5 {
 6     int n=strlen(s);
 7     for(int i=0;i<n;i++)
 8         if(s[(p+i)%n]!=s[(q+i)%n])
 9             return s[(p+i)%n]<s[(q+i)%n]; //比较两个字符串的大小,输出较小的
10         return 0; //相等
11 }
12 int main()
13 {
14     int T;
15     char s[maxn];
16     scanf("%d",&T);
17     while(T--)
18     {
19         scanf("%s",s);
20         int ans=0;
21         int n=strlen(s);
22         for(int i=1;i<n;i++)
23             if(less(s,i,ans)) ans=i; //将较小的字符串赋值给ans
24         for(int i=0;i<n;i++)
25             putchar(s[(i+ans)%n]);
26         putchar('\n');
27     }
28     return 0;
29 }

 

























posted @ 2017-08-02 15:35  糖小俊  阅读(990)  评论(0编辑  收藏  举报