Lightoj 1166 - Old Sorting (简单贪心)

27 篇文章 1 订阅

1166 - Old Sorting
Time Limit: 2 second(s)Memory Limit: 32 MB

Given an array containing a permutation of 1 to n, you have to find the minimum number of swaps to sort the array in ascending order. A swap means, you can exchange any two elements of the array.

For example, let n = 4, and the array be 4 2 3 1, then you can sort it in ascending order in just 1 swaps (by swapping 4 and 1).

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains two lines, the first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers separated by spaces. You may assume that the array will always contain a permutation of 1 to n.

Output

For each case, print the case number and the minimum number of swaps required to sort the array in ascending order.

Sample Input

Output for Sample Input

3

4

4 2 3 1

4

4 3 2 1

4

1 2 3 4

Case 1: 1

Case 2: 2

Case 3: 0





题意:把一个序列换成递增序列最少需要交换多少次
思路:因为只能是交换两个,而不是像hdu5500改变一个的位置,所以就直接遇到一个把一个恢复原位就好了。。。因为是交换,两个位置都要变,所以只要是复位,怎么变都一样。。没有最短。。
n方复杂度:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 104;
int a[maxn];
int main()
{
    int t, n, ca = 1;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        int ans = 0;
        for(int i = 1;i <= n; i++)
        {
            if(a[i] != i)
            {
                for(int j = i + 1; j <= n; j++)
                {
                    if(a[j] == i)
                        swap(a[i], a[j]);
                }
                    ans++;
            }
        }
        printf("Case %d: %d\n", ca++, ans);
    }
    return 0;
}
重新开个数组,o(n)复杂度
#include<bits/stdc++.h>  
using namespace std;  
#define ll long long  
#define ull unsigned long long  
#define mod 100000007  
#define inf 0x3f3f3f3f  
int a[120],b[120];  
int main()  
{  
    int t;  
    scanf("%d",&t);  
    for(int cas=1;cas<=t;cas++)  
    {  
        int n;  
        scanf("%d",&n);  
        for(int i=1;i<=n;i++)  
        {  
            scanf("%d",&a[i]);  
            b[a[i]]=i;  
        }  
        int ans=0;  
        for(int i=1;i<=n;i++)  
        {  
            if(a[i]==i) continue;  
            int tmp=b[i];  
            b[a[i]]=tmp;  
            swap(a[i],a[tmp]);  
            ans++;  
        }  
        printf("Case %d: %d\n",cas,ans);  
    }  
    return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值