UVA1584 - Circular Sequence 循环字符串比较的技巧

来源:互联网 发布:mac安装双系统win8 编辑:程序博客网 时间:2024/04/26 22:31

题目如下:

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.

\epsfbox{p3225.eps}

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 casesT 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

一开始拿到这个题,首先想到的是用多个数组储存每次变化后的字符串,然后用数组进行比较。这样做不仅会消耗大量空间和时间,程序也会特别繁琐。

让我们想一下问题的实质在哪里?

比较。

如何去比较?

肯定是对应元素一个一个比较。

换一种说法,就是两个差值恒定的下标作比较。我们只需要移动下标即可。

从这个角度看,我们发现这有点像在寻找 “最小值”:将两种元素以一定的方式进行比较。


代码如下:

#include<stdio.h>#include<string.h>int judge(char*A,int key, int p,int flag){while(key < flag) {//将元素一个一个进行比较 if(A[key%strlen(A)] > A[p%strlen(A)])return 1;else if(A[key%strlen(A)] == A[p%strlen(A)]) {key++;p++;if( judge(A,key,p,flag) )return 1;}else return 0;}}int main(){int T;char A[110];char B[110];scanf("%d",&T);while(T--){memset(A,0,sizeof(A));memset(B,0,sizeof(B));scanf("%s",A);int key=0,p=1;while(p<strlen(A)){//寻找使得“最小”成立的下标key int flag = key+strlen(A);if( judge(A,key,p,flag) )key = p;p++;}for(int i=0;i<strlen(A);i++){//找到下标key后,将数组转移到一个新的数组中,方便输出。 B[i] = A[key%strlen(A)];key++;}printf("%s\n",B);}

0 0
原创粉丝点击