UVa11858 - Frosh Week(树状数组求逆序数)

来源:互联网 发布:天津天狮网络主打歌曲 编辑:程序博客网 时间:2024/05/17 03:17

During Frosh Week, students play various fun games to get to know eachother and compete against other teams. In one such game, all the froshon a team stand in a line, and are then asked to arrange themselvesaccording to some criterion, such as their height, their birth date,or their student number. This rearrangement of the line must beaccomplished only by successively swapping pairs of consecutive students.The team that finishes fastest wins. Thus, in order to win,you would like to minimizethe number of swaps required.

Input Specification

Input contains several test cases. For each test case, the first line of input contains one positive integer n, the number of studentson the team, which will be no more than one million. The following n lineseach contain one integer, the student number of each student on the team.No student number will appear more than once.

Sample Input

3312

Output Specification

For each test case, output a line containing the minimum number of swapsrequired to arrange the students in increasing order by student number.

Output for Sample Input

2

树状数组求逆序数

1、离散化,将输入的数据从小到大排序,同时将原来数据的原始位置与当前位置映射

2、统计比当前插入的数大的个数,边插入边相加

import java.io.FileInputStream;import java.io.BufferedInputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.util.Scanner;import java.util.Arrays;public class Main implements Runnable{private static final boolean DEBUG = false;private PrintWriter cout;private Scanner cin;private int n;private int[] a;private long[] c;class Node implements Comparable<Node>{int val, pos;public int compareTo(Node other){return val - other.val;}}private void init(){try {if (DEBUG) {cin = new Scanner(new BufferedInputStream(new FileInputStream("d:\\OJ\\uva_in.txt")));} else {cin = new Scanner(new BufferedInputStream(System.in));}cout = new PrintWriter(new OutputStreamWriter(System.out));} catch (Exception e) {e.printStackTrace();}}private boolean input(){if (!cin.hasNextInt()) return false;n = cin.nextInt();Node[] node = new Node[n + 1];for (int i = 1; i <= n; i++) {node[i] = new Node();node[i].val = cin.nextInt();node[i].pos = i;}Arrays.sort(node, 1, n + 1);a = new int[n + 1];c = new long[n + 1];for (int i = 1; i <= n; i++) {a[node[i].pos] = i;}return true;}private int lowbit(int x){return x & (-x);}private void update(int x, int v){while (x <= n) {c[x] += v;x += lowbit(x);}}private long sum(int x){long ans = 0;while (x > 0) {ans += c[x];x -= lowbit(x);}return ans;}private void solve(){long ans = 0;for (int i = 1; i <= n; i++) {update(a[i], 1);ans += i - sum(a[i]);}cout.println(ans);cout.flush();}public void run(){init();while (input()) {solve();}}public static void main(String[] args){new Thread(new Main()).start();}}


0 0
原创粉丝点击