題目:M – 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.
Input
The 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.
Output
For 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
大意:就是將輸入的數列進行升序排列的過程中,相鄰的兩個兩兩交換的次數最少為多少;
思路:這個題不能單純的用什麼冒泡啥的,顯然不行,而是求出其對應的逆序數的對數,求出之後,有多少對就是進行移動的最少的次數。這是因為對於逆序數的時候你可以先交換相鄰的逆序數,最後一定能讓不相鄰的逆序數變成相鄰,然後交換,所以有多少對逆序數就最少移動多少次;
新技巧:對於一個序列移動最少次數的時候,等會了快速排序和sort內部的函式之後就更明白了,現在就先理解在數值上與逆序數的對數相同;(逆序數:以陣列為例,兩個陣列元素比較,下標小的但數值大);(這裡是應用了逆序數與其排序之間的關係,學會聯絡不同的關係,然後再處理問題的時候進行相應的轉化);
程式碼:
#include<stdio.h>
int main()
{
int i,j,m,n,a[1005];
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
m=0;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
m++;
printf("%d
",m);
}
return 0;
}