hdu4000-樹狀數組-2

來源:互聯網
上載者:User

 http://acm.hdu.edu.cn/showproblem.php?pid=4000

題意:對1--n的一個排列,求所有的i<j<k且a[i]<a[k]<a[j]的個數。。。

 

分析:比賽的時候總是想不出來怎麼做,老想著單純枚舉i或者j或者k來求得結果,不知道變通。。。實際上可以換個方向思考,對每個位置考慮後面有多少比他大的數,則這個小的後面跟兩個大的個數為x(x-1)/2,然後肯定要減去後面的所有組成的i<j<k且a[i]<a[j]<a[k]的個數,這兩種操作都可以解決,則問題就轉化為掃描一遍數組而已了。。。

 

代碼:

#include <stdio.h>#include <iostream>using namespace std;const int N=100001;int a, n, f[N];__int64 ans, tmp, tmp1;void insert(int i){for(; i<=n; i+=i&(-i))f[i] += 1;}int query(int i){int tmp=0;for(; i>0; i-=i&(-i))tmp += f[i];return tmp;}int main(){int i, cas, cas1=1;scanf("%d", &cas);while(cas--){scanf("%d", &n);ans = 0;for(i=1; i<=n; i++)f[i] = 0;for(i=1; i<=n; i++){scanf("%d", &a);insert(a);tmp = query(a-1);tmp1 = (n-a)-(i-1-tmp);ans -= tmp*tmp1;if(tmp1>=2)ans += tmp1*(tmp1-1)/2;}printf("Case #%d: %I64d\n", cas1++, ans%100000007);}return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.