[关闭]
@zhangche0526 2017-02-25T06:33:39.000000Z 字数 860 阅读 1067

树状数组求逆序对

模板


  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. #include<algorithm>
  5. using namespace std;
  6. typedef long long ll;
  7. const int MAXN = 100000;
  8. ll n, cnt, a[MAXN + 1], b[MAXN + 1];//b:树状数组,ls:离散后数组
  9. ll k;
  10. struct mark
  11. {
  12. ll n, ln;//数值,原先编号;
  13. } ls[MAXN + 1];
  14. ll lowbit(ll x){return x & (- x);}
  15. void add(ll x, ll y)//x处加上y
  16. {
  17. for(; x <= n; x += lowbit(x))
  18. {
  19. b[x] += y;
  20. }
  21. }
  22. ll sum(ll x)
  23. {
  24. ll ans = 0;
  25. for(; x; x -= lowbit(x)) ans += b[x];
  26. return ans;
  27. }
  28. int cmp(const mark & a, const mark & b){return a.n < b.n;}
  29. int main()
  30. {
  31. int i, j;
  32. ios::sync_with_stdio(false);
  33. while(cin >> n >> k)
  34. {
  35. memset(a, 0, sizeof(a));
  36. memset(b, 0, sizeof(b));
  37. memset(ls, 0, sizeof(ls));
  38. for(i = 1; i <= n; i ++) cin >> a[i], ls[i].n = a[i], ls[i].ln = i;
  39. sort(ls + 1, ls + n + 1, cmp);
  40. cnt = 1;
  41. a[ls[1].ln] = cnt;
  42. for(i = 2; i <= n; i ++)
  43. {
  44. if((ls[i - 1].n != ls[i].n)) cnt ++;
  45. a[ls[i].ln] = cnt;
  46. }
  47. ll ans = 0;
  48. for(i = n; i >= 1; i--)
  49. {
  50. ans += sum(a[i] - 1);
  51. add(a[i], 1);
  52. }
  53. if(ans - k < 0) cout << 0 << endl;
  54. else cout << ans - k << endl;
  55. }
  56. return 0;
  57. }

题目:

HDU 4911
HDU 3743
HDU 1394
HDU 5497
NOIP 2012

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注