Reduce inversion count

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

Description

Find a pair in an integer array that swapping them would maximally decrease the inversion count of the array. If such a pair exists, return the new inversion count; otherwise returns the original inversion count.

Definition of Inversion: Let (A[0], A[1] ... A[n], n <= 50) be a sequence of n numbers. If i < j and A[i] > A[j], then the pair (i, j) is called inversion of A.

Example:
Count(Inversion({3, 1, 2})) = Count({3, 1}, {3, 2}) = 2
InversionCountOfSwap({3, 1, 2})=>
{
 InversionCount({1, 3, 2}) = 1 <-- swapping 1 with 3, decreases inversion count by 1
 InversionCount({2, 1, 3}) = 1 <-- swapping 2 with 3, decreases inversion count by 1
 InversionCount({3, 2, 1}) = 3 <-- swapping 1 with 2 , increases inversion count by 1
}


Input

Input consists of multiple cases, one case per line.Each case consists of a sequence of integers separated by comma.

Output

For each case, print exactly one line with the new inversion count or the original inversion count if it cannot be reduced.


样例输入
3,1,2
1,2,3,4,5
样例输出
1
0
我的java代码。。。求大神不吝赐教。
package com.summer.intern;
import java.util.Scanner;
public class Main {
    public static int getInversionCount(int data[])
    {
        int count=0;
        for(int i=0;i<data.length;i++){
            for(int j=i+1;j<data.length;j++)
            {
                if(data[i]>data[j]) count++;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNextLine()) {
            String line = input.nextLine();
            String num[] = line.split(",");
            int data[]=null;
            data=new int [num.length];
            for(int i=0;i<num.length;i++)
            {
                data[i]=Integer.parseInt(num[i]);
            }
            int orial_inversion_count=getInversionCount(data);
            int temp_data[]=data.clone();
            for(int i=0;i<data.length;i++){
                for(int j=i+1;j<data.length;j++){
                    int temp=temp_data[i];
                    temp_data[i]=temp_data[j];
                    temp_data[j]=temp;
                    int now_inversion_count=getInversionCount(temp_data);
                    if(orial_inversion_count>now_inversion_count)
                    {
                        orial_inversion_count=now_inversion_count;
                    }
                    temp_data=data.clone();
                }
            }
            System.out.println(orial_inversion_count);
        }
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值