poj--2299(树状数组+离散化)

时间:2023-03-08 19:17:58

一、离散化:

https://www.cnblogs.com/2018zxy/p/10104393.html

二、逆序数

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn = ;
struct Node{
LL data;
int val;
}cur[maxn];
LL a[maxn];
bool cmp(Node A,Node B)
{
return A.data<B.data;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
while(x<maxn-)
{
a[x]++;
x+=lowbit(x);
}
}
int sum(int x)
{
int ans=;
while(x>)
{
ans+=a[x];
x-=lowbit(x);
}
return ans;
}
int main(void)
{
int n,i;
while(~scanf("%d",&n)&&n)
{
memset(a,,sizeof(a));
for(i=;i<=n;i++)
{
scanf("%lld",&cur[i].data);cur[i].val=i;
}
sort(cur+,cur++n,cmp);
LL ans=;
for(i=;i<=n;i++)
{
update(cur[i].val);
ans+=i-sum(cur[i].val);
}
printf("%lld\n",ans);
}
return ;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn = ;
struct Node{
LL data;
int val;
}cur[maxn];
LL a[maxn];
bool cmp(Node A,Node B)
{
return A.data<B.data;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
while(x<maxn-)
{
a[x]++;
x+=lowbit(x);
}
}
int sum(int x)
{
int ans=;
while(x>)
{
ans+=a[x];
x-=lowbit(x);
}
return ans;
}
int main(void)
{
int n,i;
while(~scanf("%d",&n)&&n)
{
memset(a,,sizeof(a));
for(i=;i<=n;i++)
{
scanf("%lld",&cur[i].data);cur[i].val=i;
}
sort(cur+,cur++n,cmp);
LL ans=;
for(i=n;i>=;i--)
{
ans+=sum(cur[i].val);
update(cur[i].val);
}
printf("%lld\n",ans);
}
return ;
}