HDU - 2689 Sort it与2016蓝桥杯B 交换瓶子 排序(相邻交换与任意交换)
2017-08-11 15:49
337 查看
Sort it
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
InputThe input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.OutputFor each case, output the minimum times need to sort it in ascending order on a single line.Sample Input
3 1 2 3 4 4 3 2 1
Sample Output
0 6
交换瓶子
题目叙述:有N个瓶子,编号 1 ~ N,放在架子上。
比如有5个瓶子:
2 1 3 5 4
要求每次拿起2个瓶子,交换它们的位置。
经过若干次后,使得瓶子的序号为:
1 2 3 4 5
对于这么简单的情况,显然,至少需要交换2次就可以复位。
如果瓶子更多呢?你可以通过编程来解决。
输入格式为两行:
第一行: 一个正整数N(N<10000), 表示瓶子的数目
第二行:N个正整数,用空格分开,表示瓶子目前的排列情况。
输出数据为一行一个正整数,表示至少交换多少次,才能完成排序。
例如,输入:
5
3 1 2 5 4
程序应该输出:
3
再例如,输入:
5
5 4 3 2 1
程序应该输出:
2
资源约定:
峰值内存消耗 < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程设置而省略常用头文件。
提交时,注意选择所期望的编译器类型。
第一题交换条件是相邻两个数,第二题则是任意两个数。很显然冒泡排序模拟了相邻交换,所以第一题用冒泡排序,记录交换次数;第二题没有限制,所以每次交换都将当前数换到正确的位置,贪心即可。
//第一题 #include<stdio.h> int main() { int n,c,t,i,j; int a[1005]; while(~scanf("%d",&n)){ for(i=1;i<=n;i++){ scanf("%d",&a[i]); } c=0; for(i=1;i<=n;i++){ for(j=1;j<=n-i;j++){ if(a[j]>a[j+1]){ c++; t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } printf("%d\n",c); } return 0; }
//第二题 #include<stdio.h> #include<stdlib.h> int main(){ int n,*num,i,tmp,count=0; scanf("%d",&n); num=(int *)malloc(sizeof(int)*(n+1)); for(i=1;i<=n;i++){ scanf("%d",&num[i]); } rep: for(i=1;i<=n;i++){ if(i==num[i])continue; tmp=num[i]; num[i]=num[tmp]; num[tmp]=tmp; count++; goto rep; } printf("%d",count); return 0; }
相关文章推荐
- HDU2689-树状数组&逆序数|分治-Sort it
- HDU 2689 Sort it
- HDU2689 Sort it (树状数组求逆序数)
- HDU 2689 Sort it
- 2016第七届蓝桥杯 第九题 :交换瓶子(两种方法)
- HDU 2689 sort it - from lanshui_Yang
- HDU 2689 Sort it(树状数组,逆序数)
- HDU 2689 Sort it(树状数组)(类似逆序数,同样不需要离散化)
- HDU - 2689 Sort it
- 【树状数组+简单题】杭电 hdu 2689 Sort it
- hdu2689 Sort it (树状数组)
- HDU 2689 sort it
- HDU 2689 Sort it
- HDU-2689-Sort it
- hdu2689 Sort it
- HDU-2689-Sort it
- HDU 2689 Sort it
- hdu 2689 Sort it(线段树)
- HDU 2689 Sort it 求逆序数,树状数组实现
- hdu 2689 Sort it