荷兰国旗,三类数字分离 nyoj

很有用O(n)内实现三类数字分离,以前大多是分成两类数据,快排中分成两类,还有就是“ab***vvvc” 在O(n)中变成 abvvc****,变成两类划分问题
 
#include<iostream>
#include<string.h>
using namespace std;
const int N=1000;
char c[N];
int len;
 void swap(char &a,char &b)
{
    //a=a^b;
    //b=a^b;
    //a=a^b;
    char c=a;
       a=b;
       b=c;

}
 void display()
 {
 for(int i=0;i<len;i++)
            {
        cout<<c[i];
            }
 
 }
int main()
{
    int len2;
    cin>>len2;
    while(len2--)
    {
        cin>>c;
         len=strlen(c);
        cout<<"长度为"<<len<<endl;
        int beg=0; 
        int end=len-1;
        int cur=0;
            while(cur<=end)
            {
                if(c[cur]=='R')
                {
                   swap(c[cur],c[beg]);
                 //  cout<<"swapR"<<cur<<"---and--"<<beg<<endl;
                 
                   beg++;
                   cur++;
                
                
                }
                
                else if(c[cur]=='W')
                {
                    cur++;

                
                
                }
                else
                {
                    swap(c[cur],c[end]);
                    // cout<<"swapB"<<cur<<"---and--"<<end<<endl;
                    end--;
                    

                
                
                }

            cout<<"正在进行"<<endl;
            
            
            }
            display();
    
       cout<<endl;
    }
    system("pause");
return 0;
}
posted @ 2014-05-17 20:33  hansongjiang8  阅读(185)  评论(0编辑  收藏  举报