HDU - 2689 Sort it与2016蓝桥杯B 交换瓶子 排序(相邻交换与任意交换)

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个正整数,用空格分开,表示瓶子目前的排列情况。

输出数据为一行一个正整数,表示至少交换多少次,才能完成排序。

例如,输入: 

3 1 2 5 4

程序应该输出: 
3

再例如,输入: 

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<bits/stdc++.h>
#define MAX 200005
#define INF 0x3f3f3f3f
#define MOD 1000000007
using namespace std;
typedef long long ll;

int a[MAX];

int main()
{
    int t,n,i,j;
    while(~scanf("%d",&n)){
        for(i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        int ans=0;
        for(i=1;i<=n;i++){
            while(a[i]!=i){
                t=a[i];
                a[i]=a[t];
                a[t]=t;
                ans++;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2017-08-11 15:49  yzm10  阅读(324)  评论(0编辑  收藏  举报