HDU2838-簡單樹狀陣列
阿新 • • 發佈:2019-01-29
這道題分析一下,開兩個樹狀陣列分別儲存前i個數的和以及前i個數的個數,然後每次查詢一下就好了,注意這裡儲存字首和的陣列會超int,需要開成long long,題目如下:
Cow Sorting
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3521 Accepted Submission(s): 1222
Problem Description Sherlock's N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock's milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.
Please help Sherlock calculate the minimal time required to reorder the cows.
Input Line 1: A single integer: N
Lines 2..N + 1: Each line contains a single integer: line i + 1 describes the grumpiness of cow i.
Output Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.
Sample Input 3 2 3 1
Sample Output 7 Hint
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll c[100010]; ll num[100010]; int lowbit(int x) { return x&(-x); } void update(int x, int val) { for(; x <= 100010; x += lowbit(x)) c[x] += (ll)val; } ll query(int x) { if(x == 0) return 0; ll sum = 0; for(; x > 0; x -= lowbit(x)) { sum += (ll)c[x]; } return sum; } void update1(int x, int val) { for(; x <= 100010; x += lowbit(x)) num[x] += val; } int query1(int x) { if(x == 0) return 0; int sum = 0; for(; x > 0; x -= lowbit(x)) { sum += num[x]; } return sum; } int main() { int n; while(~scanf("%d", &n)) { memset(c, 0, sizeof(c)); memset(num, 0, sizeof(num)); ll sum = 0, ans = 0; for(int i = 1; i <= n; i++) { int t; scanf("%d", &t); ans = ans + sum - query(t-1) + (i-1-(ll)query1(t-1))*(ll)t; update(t, t); update1(t, 1); sum += (ll)t; //printf("%lld\n", ans); } printf("%lld\n", ans); } return 0; }#include<bits/stdc++.h> using namespace std; typedef long long ll; ll c[100010]; ll num[100010]; int lowbit(int x) { return x&(-x); } void update(int x, int val) { for(; x <= 100010; x += lowbit(x)) c[x] += (ll)val; } ll query(int x) { if(x == 0) return 0; ll sum = 0; for(; x > 0; x -= lowbit(x)) { sum += (ll)c[x]; } return sum; } void update1(int x, int val) { for(; x <= 100010; x += lowbit(x)) num[x] += val; } int query1(int x) { if(x == 0) return 0; int sum = 0; for(; x > 0; x -= lowbit(x)) { sum += num[x]; } return sum; } int main() { int n; while(~scanf("%d", &n)) { memset(c, 0, sizeof(c)); memset(num, 0, sizeof(num)); ll sum = 0, ans = 0; for(int i = 1; i <= n; i++) { int t; scanf("%d", &t); ans = ans + sum - query(t-1) + (i-1-(ll)query1(t-1))*(ll)t; update(t, t); update1(t, 1); sum += (ll)t; //printf("%lld\n", ans); } printf("%lld\n", ans); } return 0; }