题目描述
The Dutch flag problem is to rearrange an array of characters R, W,and B (red, white, and blue are the colors of the Dutch national flag) so that all the R’s come first, the W’s come next, and the B’s come last. Design a linear and stable algorithm for this problem.
输入
two lines, the first line is total of numbers characters R,W and B ,and the numbers less than 500005 the second line is random characters R,W and B
输出
a line, all the R’s come first, the W’s come next, and the B’s come last.
#include<bits/stdc++.h>
using namespace std;
int main()
{
char x;
int n;
cin>>n;
char a[n+1];
for(int i=0; i<n; i++)
{
cin>>a[i];
}
int r=0,w=0,b=n-1;
while(w<=b)
{
x=a[w];
if(a[w]=='R')
{
a[w]=a[r];
a[r]=x;
w++;
r++;
}
else if(a[w]=='W')
{
w++;
}
else
{
a[w]=a[b];
a[b]=x;
b--;
}
}
for(int i=0; i<n; i++)
{
cout<<a[i];
}
cout<<endl;
return 0;
}