蓝桥杯 小朋友排队+

蓝桥杯 历届试题 小朋友排序 

在这里用的树状数组和离线化

有不足之处还请大牛指出!

并没有 百分百正确 只通过了60%的数据测试

希望java大牛看到后能提出优化改进


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	static int[] old;
	static int[] now;
	static int[] treearray;
	static int[] left;
	static int[] right;
	static int[] hight;
	static int a;

	// static int n;
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		a = sc.nextInt();
		old = new int[a + 1];
		now = new int[a + 1];
		treearray = new int[a + 1];
		for (int i = 1; i < old.length; i++) {
			now[i] = old[i] = sc.nextInt();
		}
		//
		Arrays.sort(old);
		int k = 1;
		Map hs = new HashMap();
		for (int i = 1; i < old.length; i++) {
			hs.put(old[i], k++);
		}
		for (int i = 1; i < now.length; i++) {
			now[i] = hs.get(now[i]);
		}
		//
		left = new int[a + 1];

		for (int i = 1; i <= a; i++) {
			update(now[i], 1);
			left[i] = i - getSum(now[i]);
		}
		// sop(left);
		//
		right = new int[a + 1];
		treearray = new int[a + 1];
		for (int f = a; f >= 1; f--) {
			update(now[f], 1);
			right[f] = getSum(now[f] - 1);
		}
		// sop(right);

		//
		hight = new int[a + 1];
		for (int i = 1; i <= a; i++) {
			hight[i] = left[i] + right[i];
		}
		long ans = 0;
		for (int i = 1; i <= a; i++) {
			ans += (1 + hight[i]) * hight[i] / 2;
		}
		System.out.println(ans);

	}

	public static void update(int t, int x) {
		for (int i = t; i < a + 1; i += lowbit(i)) {
			treearray[i] += x;
		}
	}

	public static int getSum(int x) {
		int temp = 0;
		for (int j = x; j >= 1; j -= lowbit(j)) {
			temp += treearray[j];
		}
		return temp;
	}

	private static int lowbit(int x) {
		// TODO Auto-generated method stub
		return x & -x;
	}
}

蓝桥杯 小朋友排队+_第1张图片

你可能感兴趣的:(蓝桥杯)