题目大意 就是求逆序数对,至于求法有多种可以用 归并、树状数组、线段树等,下面直接贴代码)第一次写博客
#include <set>
#include <map>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf = 0x3f3f3f3f;
const int maxn = 100010;
int c[maxn];
int a[maxn];
int n,k;
struct node
{
int x,y;
}p[maxn];
int lowbit (int x)
{
return x & -x;
}
ll sum(int x)
{
ll ans = 0;
while (x)
{
ans += c[x];
x -= lowbit(x);
}
return ans;
}
void add(int x,int d)
{
while (x < 100005)
{
c[x] += d;
x += lowbit(x);
}
}
bool cmp(node p1,node p2)
{
return p1.x < p2.x;
}
int main(void)
{
ios_base::sync_with_stdio(false);
while (cin>>n>>k)
{
memset(c,0,sizeof(c));
for (int i = 0; i < n; i++)
{
cin>>p[i].x;
p[i].y = i+1;
}
sort (p,p+n,cmp); //数据较大进行离散化
int t;
for (int i = 0,j = 1; i < n; i++)
{
if (i&&p[i-1].x==p[i].x)
a[p[i].y] = t;
else
a[p[i].y] = j,t=j++;
}
ll ans = 0; //求逆序数对
for (int i = 1; i <= n; i++)
{
ans += i -1- sum(a[i]);
add(a[i],1);
}
if (k<ans)
cout<<ans-k<<endl;
else
cout<<0<<endl;
}
return 0;
}