题目: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.
Sample Input
2
CGAGTCAGCT
CTCC
Sample Output
AGCTCGAGTC
CCCT
分析:题目意思直接就是给你一个环的所有元素,然后以每一个字母为首元素构成一个一个环,比如CTCC可以构成"CTCC、TCCC、CCCT、CCTC"这些环,最后求这些环的最小字典序。
这里需要了解字典序的概念,设想一本英语字典里的单词,何者在前何者在后?显然的做法是先按照第一个字母、以 a、b、c……z 的顺序排列;如果第一个字母一样,那么比较第二个、第三个乃至后面的字母。如果比到最后两个单词不一样长(比如,sigh 和 sight),那么把短者排在前。通过这种方法,我们可以给本来不相关的单词强行规定出一个顺序,这就是字典序。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
string a,c;
string b[100];
cin>>n;
while(n--){
cin>>a;
for(int i=0;i<a.size();++i){ //直接的做法,把所有的环求出来
if(!i) b[i]=a,c+=a[i];
else{
for(int j=i;j<a.size();++j)
b[i]+=a[j];
b[i]+=c;
c+=a[i];
}
}
sort(b,b+a.size());//排序
cout<<b[0]<<endl;
for(int i=0;i<a.size();++i)
b[i]="";
c.clear();//对下次操作更新
}
return 0;
}