算法分析之三色旗算法

一条绳子挂红白蓝三种颜色的旗子,且排列无序,现用程序把三种旗子同色归类,顺序为蓝-白-红,每次只能交换2面旗子,采用最少步骤完成。

算法描述:只需把红色和蓝色的旗子进行交换,红旗和篮旗都就位后,白旗自然就位。

1) 如果白旗所在位置的元素是白旗,表示该位置的元素应该在此,将white++,接着处理下一个旗子;

2) 如果white所在位置的元素是蓝旗,表示需将蓝旗与blue变量所在位置的元素对调,然后使blue++、white++,处理下一个旗子;

3) 如果white所在位置的元素是红旗,表示需要将红旗与red变量的元素对调,然后将red--,继续处理下一旗子。

 

 

 1 namespace section10_threeFlags{
 2 int count;
 3 char color[]="rwbwwbrbwr";
 4 int blue,white,red;
 5 //exchange variable a and b
 6 void swap(char * a, char *b){
 7     char temp;
 8     int i;
 9     temp = *a;
10     *a=*b;
11     *b=temp;
12     count++;
13     printf("the %dth order exchanged\n",count);
14     for(i=0;i<(int)strlen(color);i++){
15             printf("%c ",color[i]);
16     }
17     printf("\n");
18 }
19 void threeFlags(){
20     while(color[white]=='b'){
21         blue++;
22         white++;
23     }
24     while(color[red]=='r'){
25         red--;
26     }
27     while(white<=red){
28         if(color[white]=='r'){
29             swap(&color[white],&color[red]);
30             red--;
31             while(color[red]=='r'){
32                 red--;
33             }
34         }
35         while(color[white]=='w'){
36             white++;
37         }
38         if(color[white]=='b'){
39             swap(&color[white],&color[blue]);
40             blue++;
41             white++;
42         }
43     }
44 }
45 void runThreeFlags(){
46     int i,len;
47     blue=white=0;
48     len=strlen(color);
49     red=len-1;
50     count=0;
51     printf("The original flags' array are as follows:\n ");
52     for(i=0;i<len;i++){
53         printf("%c ",color[i]);
54     }
55     printf("\n");
56     threeFlags();
57     printf("The last result :\n");
58     for(i=0;i<len;i++){
59         printf("%c ",color[i]);
60     }
61     printf("\n");
62 }

 

转载于:https://www.cnblogs.com/hoojjack/p/5208075.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值