题目链接:http://poj.org/problem?id=2299
离散化 + 树状数组
教科书例题般的题目
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <cmath> #include <vector> #include <stack> #include <set> #include <map> #include <algorithm> #include <sstream> using namespace std; typedef long long ll; const int maxn = 500010; struct pre { int num, id; bool operator < (const pre &b) const { return num < b.num; } }p[maxn]; int a[maxn], bit[maxn], n; int sum(int i) { int s = 0; while(i > 0) { s += bit[i]; i -= i & -i; } return s; } void add(int i, int x) { while(i <= n) { bit[i] += x; i += i & -i; } } int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif while(scanf("%d", &n) == 1 && n) { for(int i = 0; i < n; i++) { scanf("%d", &p[i].num); p[i].id = i; } sort(p, p + n); for(int i = 1; i <= n; i++) { a[p[i-1].id] = i; } ll ans = 0; for(int j = 0; j < n; j++) { ans += j - sum(a[j]); add(a[j], 1); } printf("%I64d\n", ans); for(int i = 0; i <= n; i++) { bit[i] = 0; } } return 0; }
时间: 2024-12-24 17:41:26