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
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
- 2015笔试上机题-- 求01串的最小交换次数
- [阿里一道笔试题]排序的交换次数
- 只含0、1的串进行排序,可任意交换位置,最小交换次数
- 微软笔试题 求出现次数超过一半的元素
- 2015笔试上机题--求员工就餐最大享受度
- 关于一个求最小交换次数的算法的一个严格证明,是严格证明,不是想当然
- Ultra-QuickSort 求最小交换次数即求逆序对数 树状数组+离散化
- 面试题笔试题——数组排序交换次数
- poj 1654--重新排序求交换的次数
- UVA331求排序过程交换次数最少的种类数
- [笔试题]求自然数0-1000000中1出现的次数
- 【前端笔试题】给定数字N,求从1到N中间0出现的次数
- KMP求最小重复子串的重复次数(poj2406)
- 数组排序--计算最小交换次数
- 1到n打乱,求交换次数
- 笔试题:求数组中和为sum的乘积最小的一对组合
- 51Nod1574(新姿势:使序列有序的最小交换次数)
- NEU1511 Caoshen like math(使序列有序的最小交换次数)
- 杭电 HDU ACM 1398 Square Coins
- C++ string的实现
- 唤醒锁: 检测 Android* 应用中的 No-Sleep(无法进入睡眠)问题
- HDU4786 Fibonacci Tree【最小生成树】
- Eclipse新建Android项目后,出现“The import android.support.v7.app cannot be resolved”
- 2015笔试上机题-- 求01串的最小交换次数
- 简单工厂、工厂模式、抽象工厂三种模式的对比与总结
- 【总结】性能调优:消耗分析
- vi, sed 等程序竟然后改变文件 inode!!!
- JAVA基础——网络编程
- VS MFC获取文件路径
- 第八周项目一 运算符重载
- 智力题
- C Primer Plus 第七章程序清单……2014.4.24