sgu 180 Inversions
题意:逆序对组数。
用树状数组或归并排序,经典问题。注意结果long long。
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <iomanip> #include <cstring> #include <map> #include <queue> #include <set> #include <cassert> #define mkp make_pair using namespace std; const double EPS=1e-8; typedef long long lon; const int SZ=70010,INF=0x7FFFFFFF; int n; vector<int> vct,ls; int arr[SZ]; void init() { cin>>n; vct.assign(n,0); for(int i=0;i<n;++i) { cin>>vct[i]; ls.push_back(vct[i]); } ls.push_back(-1); sort(ls.begin(),ls.end()); ls.erase(unique(ls.begin(),ls.end()),ls.end()); } int lowbit(int x) { return x&-x; } int qry(int x) { int res=0; //x-=lowbit(x); for(;x;x-=lowbit(x)) { res+=arr[x]; } return res; } void add(int x) { //x-=lowbit(x); for(;x<SZ;x+=lowbit(x)) { ++arr[x]; } } void work() { lon res=0; for(int i=0;i<vct.size();++i) { int pos=lower_bound(ls.begin(),ls.end(),vct[i])-ls.begin(); res+=i-qry(pos); add(pos); } cout<<res<<endl; } int main() { std::ios::sync_with_stdio(0); //freopen("d:\\1.txt","r",stdin); lon casenum; //cin>>casenum; //for(lon time=1;time<=casenum;++time) { init(); work(); } return 0; }