首页 > 其他 > 详细

Circular Sequence UVa1584

时间:2018-08-01 15:45:09      阅读:182      评论:0      收藏:0      [点我收藏+]

描述:

     长度为n的环状串有n种表示方法,分别为从某个位置开始顺时针得到,在这些排列中字典顺序最小的称“最小表示”。

     如CTCC的最小表示为CCCT,CGAGTCAGCT的最小表示为AGCTCGAGTC。

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define maxn 110
 4 
 5 
 6 char a[maxn];    //the array entered by users.
 7 char b[maxn];    //the array used to save the temp array.
 8 
 9 //chang ABCD into BCDA 
10 void sort_array(char temp[], int length)
11 {
12     char fir = temp[0];
13     for (int i = 1; i<length; i++)
14     {
15         temp[i-1] = temp[i];
16     }
17     temp[i-1] = fir;
18 }
19 
20 int main()
21 {
22     scanf("%s",a);
23     strcpy(b,a);
24     int length = strlen(a);
25     for (int i = 0; i<length; i++)
26     {
27         sort_array(b, length);
28         if(strcmp(b,a) == -1) strcpy(a,b);
29     }
30     printf("%s\n",a);
31     return 0;
32 }

思路:

  1. 将环状解开变成一个一位数组,由于是环状的,所以不能随便移动元素的位置,可以选择所有元素向前推一个,然后将第一个元素放在最后,不断的重复最终得到一个最佳的答案。

注意点:

  1. strcmp中如果第一个字符串大于第二个字符串,那么返回值为1;如果第一个字符串等于第二个字符串,返回值为0;如果第一个字符串小于第二个字符串返回值为-1。

补充:

  1. 算法书中的方法用的是取mod的方法,挺有趣的,可以看看。

Circular Sequence UVa1584

原文:https://www.cnblogs.com/dreamworldclark/p/9401503.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!