1406 逆序對

來源:互聯網
上載者:User
 
描述

設A[1..n]是一個包含n個不同數的數組。如果在i<j的情況下,有A[i]>A[j],則(i, j)就稱為A中的一個逆序對。比如<2,3,8,6,1>有5個逆序對:(2,1)(3,1)(8,6)(8,1)(6,1). 現在給出一個包含不同元素的數組,請你求出這個數組中逆序對的個數。(8)


輸入

輸入為n+1行。第一行為測試資料的組數n,以下的n行分別為n組測試資料。元素為int, 用空格隔開。

輸出

輸出為n行,分別對應n組測試資料中的逆序對的個數。

範例輸入
22 3 8 6 11 2 3 4 5 6
範例輸出
50
提示

每個結點增加一個域,維護當前比這個節點大的數的數目(右子樹中元素的個數),即只要有元素插入到這個節點的右子樹,這個域的值就增1. 剩下的工作請同學自己思考。

 

類比題,用數組即可實現

#include <stdio.h>#include <string.h>char s[1000];main(){int number;int length,i,j;int p;int a[1000];int up;int temp;int count;scanf("%d",&number);getchar();while(number--){count=0;up=0;gets(s);length=strlen(s);i=0;p=0;for(i=0;i<length;i++){if(s[i]!=' '){p=0;while(s[i] >= '0' && s[i] <= '9'&&i<length){p = p * 10 + s[i] - '0';i++;}a[up++]=p;}elsecontinue;}for(i=0;i<up;i++)for(j=i+1;j<up;j++){if(a[i]>a[j])count++;}printf("%d\n",count);}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.