P7868 [COCI2015-2016#2] VUDU
将所有的数减去 $P$ ,转化为区间和大于 $0$ 。
在前缀和数组中,即
$$
s _ r - s _ {l - 1} \ge 0
\Longrightarrow s _ r \ge s _ {l - 1}
$$
即求非逆序对数。
树状数组版本,因为要离散化,所以较慢。
查看代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include <cstdio> #include <vector> #include <algorithm> using namespace std; typedef long long LL; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } const int N = 1e6 + 10; int n, m, k, w[N], tr[N]; LL s[N]; void modify(int x) { for (; x <= m; x += x & -x) tr[x]++; } int query(int x) { int res = 0; for (; x; x -= x & -x) res += tr[x]; return res; } int main() { read(n); for (int i = 1; i <= n; i++) read(w[i]); read(k); for (int i = 1; i <= n; i++) s[i] = s[i - 1] + w[i] - k; vector<LL> ws; for (int i = 0; i <= n; i++) ws.push_back(s[i]); sort(ws.begin(), ws.end()); m = ws.erase(unique(ws.begin(), ws.end()), ws.end()) - ws.begin(); for (int i = 0; i <= n; i++) s[i] = lower_bound(ws.begin(), ws.end(), s[i]) - ws.begin() + 1; modify(s[0]); LL res = 0; for (int i = 1; i <= n; i++) { res += query(s[i]); modify(s[i]); } write(res); return 0; }
|
cdq分治版本。
查看代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include <cstdio> #include <vector> #include <algorithm> using namespace std; typedef long long LL; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } const int N = 1e6 + 10; int n, m, k, w[N]; LL s[N], tmp[N]; LL cdq(int l, int r) { if (l == r) return 0; int mid = l + r >> 1; LL res = cdq(l, mid) + cdq(mid + 1, r); int i = l, j = mid + 1, t = 0; while (i <= mid && j <= r) if (s[i] <= s[j]) tmp[t++] = s[i++]; else { res += i - l; tmp[t++] = s[j++]; } while (i <= mid) tmp[t++] = s[i++]; while (j <= r) { res += mid - l + 1; tmp[t++] = s[j++]; } for (int i = l; i <= r; i++) s[i] = tmp[i - l]; return res; } int main() { read(n); for (int i = 1; i <= n; i++) read(w[i]); read(k); for (int i = 1; i <= n; i++) s[i] = s[i - 1] + w[i] - k; write(cdq(0, n)); return 0; }
|