首页 > 代码库 > HDU4911 Inversion 解题报告
HDU4911 Inversion 解题报告
题意:求逆序对
解题思路:1)树状数组 + 离散化
解题代码:
1 // File Name: a.cpp 2 // Author: darkdream 3 // Created Time: 2014年08月05日 星期二 12时05分09秒 4 5 #include<vector> 6 #include<list> 7 #include<map> 8 #include<set> 9 #include<deque>10 #include<stack>11 #include<bitset>12 #include<algorithm>13 #include<functional>14 #include<numeric>15 #include<utility>16 #include<sstream>17 #include<iostream>18 #include<iomanip>19 #include<cstdio>20 #include<cmath>21 #include<cstdlib>22 #include<cstring>23 #include<ctime>24 #define LL long long25 26 using namespace std;27 int n , k ; 28 LL sum = 0 ; 29 int lowbit(int x)30 {31 return x&(-x);32 }33 struct node{34 int num, s,rs ; 35 }a[100005];36 int num[100005];37 int getsum(int x){38 int sum = 0 ;39 while(x >= 1)40 {41 sum += num[x];42 x -= lowbit(x);43 }44 return sum ; 45 }46 void update(int x)47 {48 while(x <= n )49 {50 num[x] ++ ; 51 x += lowbit(x);52 }53 return; 54 }55 int cmp(node x ,node y )56 {57 return x.num < y.num;58 }59 int cmp1(node x, node y)60 {61 return x.s < y.s; 62 }63 int main(){64 while(scanf("%d %d",&n,&k)!= EOF)65 {66 memset(num,0,sizeof(num));67 for(int i =1;i <= n;i ++)68 {69 scanf("%d",&a[i].num);70 a[i].s = i ;71 }72 sort(a+1,a+1+n,cmp);73 int t = 1; 74 a[1].rs = 1; 75 for(int i = 2;i <= n;i ++)76 {77 if(a[i].num == a[i-1].num) 78 a[i].rs = t ;79 else {80 t++;81 a[i].rs = t; 82 }83 }84 sort(a+1,a+1+n,cmp1);85 sum = 0 ;86 for(int i = 1;i <= n;i ++)87 {88 sum += (getsum(n)- getsum(a[i].rs));89 update(a[i].rs);90 }91 if(sum > k)92 cout << sum-k << endl;93 else printf("0\n");94 }95 return 0;96 }
2)归并排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。