hdu1394求最小逆序—-樹狀數組解決

來源:互聯網
上載者:User

首先用樹狀數組求出初始序列的逆序對數,再根據變化特徵,因為所有的數都是在1 ~ n(由於用到樹狀數組每個輸進來的數都加了1) 的,所以每次把末尾的數掉到序列前面時,減少的逆序對數為n-1-A[i] ,增加的逆序對數為A[i]-1 ,這樣就可在所有的序列中找出含有逆序對最少的了!

import java.util.Arrays;import java.util.Scanner;public class hdu1394逆序數樹狀數組解決 {static int max=100003;static int c[]=new int[max];static int data[]=new int [max];static int lowbit(int i){return i&(-i);}static void modify(int k,int d){while(k<=max){c[k]+=d;k+=lowbit(k);}}static int sum(int n){int result=0;while(n>0){result+=c[n];n-=lowbit(n);}return result;}public static void main(String[] args) {Scanner in=new Scanner(System.in);while(in.hasNext()){Arrays.fill(data, 0);Arrays.fill(c, 0);int num=in.nextInt();for(int i=1;i<=num;i++){data[i]=in.nextInt();}int ans=0;for(int i=num;i>=1;i--){ans+=sum(data[i]+1);modify(data[i]+1,1);}//System.out.println(ans);int temp=ans;int result=ans;for(int i=1;i<=num;i++){ans=ans-data[i]+num-data[i]-1;if(temp<ans){result=temp;}else{result=ans;temp=ans;}}System.out.println(result);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.