2015笔试上机题-- 求01串的最小交换次数

来源:互联网 发布:铃声大全软件 编辑:程序博客网 时间:2024/09/21 06:33
题目描述:
给定一个01串(仅由 ‘0’或‘1’组成的字符串),现在把这个数字串排序成“非递减系列”,请问至少需要多少次交换(任意两个位置交换)?

Input
输入数据第一行是一个正整数T(T<100),表示有T组测试数据;
接下来的T行,每行给出一个01串。

数据包装——
50%的字符串长度在[1,100]之间;
95%的字符串长度在[1,10000];
100%的字符串长度在[1,1000000]
Output对于每组测试数据,请输出排成“非递减有序序列”所需的最小交换次数。
每组输出占一行。

Sample Input:
6
01
10
110
00100
10010011
0100100
Smaple Output:
0
1
1
1
2
2

分析:此题要求将01串按照非递减顺序排序的最小交换次数,只能是在需要交换的时候才交换,也就是将所有0移到左边,所有1放到右边所需的最小交换次数。可以利用双指针来处理。直接上C++代码:
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;int swapNum(string &s){int num = 0;string::iterator lef = s.begin();string::iterator rig = s.end()-1;while(lef < rig){if(*lef == '0')  {lef++;  /*左边指针所指元素为‘0’,则直接右移一位*/if(*rig == '1')   /*若此时右边指针所指元素为‘1’,则将其左移一位*/rig--;}else   //左指针所指元素为‘1’{if(*rig == '0')  /*此时若右边元素为‘0’,则交换两者,然后左指针右移一位,右指针左移一位*/{string::iterator tmp = lef;*lef = *rig;*rig = *tmp;num++;lef++;rig--;} else  /*若右边元素为‘1’,直接将右指针往左移,直到为‘0’*/                rig--;}}return num;}int main(void){int T;cin >> T;while(T--){string str = "";cin >> str;cout << swapNum(str) << endl;}system("pause");return 0;}

0 0