BZOJ 3289:Mato的檔案管理(莫隊演算法+樹狀數組)

來源:互聯網
上載者:User

標籤:string   size   .com   ace   fine   name   插入   mem   for   

http://www.lydsy.com/JudgeOnline/problem.php?id=3289

題意:……

思路:求交換次數即求逆序對數。確定了這個之後,先離散化數組。然後在後面插入元素的話,就是在區間裡面找比它大的元素數量,在前面插入元素的話,就是在區間裡面找比它小的元素數量。刪除操作類似。因為排序是從小到大排序,所以要找比它大的數量就是區間長度減去小於等於該元素的數量,所以是(R - L + 1 - sum(a[i])),要找比它小的數量就是(sum(a[i] - 1))。然後用莫隊演算法處理區間詢問就好了。

 1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <cmath> 5 using namespace std; 6 #define N 50010 7 struct node { 8     int l, r, id, ans; 9 } p[N];10 int bit[N], a[N], b[N], num[N], ans, kuai, n;11 12 bool cmp(const node &a, const node &b) {13     if(a.l / kuai == b.l / kuai) return a.r < b.r;14     return a.l / kuai < b.l / kuai;15 }16 bool cmpid(const node &a, const node &b) { return a.id < b.id; }17 int lowbit(int x) { return x & (-x); }18 void add(int x, int w) { for( ; x <= n; x += lowbit(x)) bit[x] += w; }19 int sum(int x) { int ans = 0; for( ; x ; x -= lowbit(x)) ans += bit[x]; return ans; }20 21 int main() {22     while(~scanf("%d", &n)) {23         for(int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i];24         int q; scanf("%d", &q);25         for(int i = 1; i <= q; i++) scanf("%d%d", &p[i].l, &p[i].r), p[i].id = i;26 27         memset(bit, 0, sizeof(bit));28         ans = 0; kuai = sqrt(n);29         sort(b + 1, b + 1 + n);30         int cnt = unique(b + 1, b + 1 + n) - b - 1;31         for(int i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + 1 + cnt, a[i]) - b;32 33         sort(p + 1, p + 1 + q, cmp);34         for(int L = 1, R = 0, i = 1; i <= q; i++) {35             int l = p[i].l, r = p[i].r;36             for( ; L < l; L++) { ans -= sum(a[L] - 1); add(a[L], -1); }37             for( ; L > l; L--) { ans += sum(a[L-1] - 1); add(a[L-1], 1); }38             for( ; R < r; R++) { ans += R - L + 1 - sum(a[R+1]); add(a[R+1], 1); }39             for( ; R > r; R--) { ans -= R - L + 1 - sum(a[R]); add(a[R], -1); }40             p[i].ans = ans;41         }42         sort(p + 1, p + 1 + q, cmpid);43         for(int i = 1; i <= q; i++) printf("%d\n", p[i].ans);44     }45     return 0;46 }

 

BZOJ 3289:Mato的檔案管理(莫隊演算法+樹狀數組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.