假设有一条绳子,上面有红、白、蓝三种颜色的旗子,起初绳子上的旗子颜色并没有顺序,您 希望将之分类,并排列为蓝、白、红的顺序,要如何移动次数才会最少,注意您只能在绳子上 进行这个动作,而且一次只能调换两个旗子。
#include <iostream>
using namespace std;
const char BLUE='b';
const char WHITE='w';
const char RED='r';
void swap(char &x,char &y)
{
char tmp=x;
x=y;
y=tmp;
}
void shuffle(char *unsorted)
{
int begin=0,current=0,end=strlen(unsorted)-1;
while(current<=end)
{
//如果当前是蓝色,把它与begin位置处的颜色交换,使之位于队列前,同时begin+1
if(unsorted[current]==BLUE)
{
swap(unsorted[current],unsorted[begin]);
begin++;
}
//如果当前是白色,则无需调换,current指向下一个
else if(unsorted[current]==WHITE)
{
current++;
}
//如果是红色,把它与end位置处的颜色交换,使之位于队列后,同时end-1
else
{
swap(unsorted[current],unsorted[end]);
end--;
}
}
}
int main()
{
char color[] = {'r', 'w', 'b', 'w', 'w','b', 'r', 'b', 'w', 'r', '\0'};
cout<<"三色旗问题:\n";
cout<<"排列前:";
for(int i=0;i<strlen(color);i++)
cout<<color[i]<<" ";
cout<<"\n\n";
shuffle(color); //对元素进行排列
cout<<"排列后:";
for(int i=0;i<strlen(color);i++)
cout<<color[i]<<" ";
cout<<"\n\n";
return 0;
}