传送门http://acm.sgu.ru/problem.php?contest=0&problem=180
经典求逆序数题目。
收获几点:
1.因为qsort关系在#11T了。改成sort就不会了。
sort用起来更方便,以后就用sort了
2.树状数组,不能从0开始,不然在lowbit()这里会陷入死循环。
3.sgu里的64位数剧 是用I64d输入输出的。这里错了一次
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define LL long long
#define bug puts("flag...")
using namespace std;
const int maxn=65555;
typedef struct sgu{
LL x,id;
}sgu;
LL hash[maxn],C[maxn];
int n;
sgu A[maxn];
bool cmp(sgu xu,sgu yi){
return xu.x<yi.x;
}
int lowbit(int x){
return x&(-x);
}
void update(int pos,int val){
while(pos>0){
C[pos]+=val;
pos-=lowbit(pos);
}
}
LL query(int x){
LL sum=0;
x+=1;
while(x<=n){
sum+=C[x];
x+=lowbit(x);
}
return sum;
}
int main(){
while(~scanf("%d",&n)){
for(int i=0;i<n;i++){
scanf("%I64d",&A[i].x);
A[i].id=i;
}
sort(A,A+n,cmp);
hash[A[0].id]=1;
int cnt=1;
for(int i=1;i<n;i++){
if(A[i].x!=A[i-1].x) cnt++;
hash[A[i].id]=cnt;
}
LL sum=0;
// memset(C,0,sizeof(C));
// for(int i=0;i<n;i++){
// printf("%lld ",hash[i]);
// }
// puts("");
for(int i=0;i<n;i++){
update(hash[i],1);
sum+=query(hash[i]);
// for(int i=0;i<n;i++){
// printf("%lld ",C[i]);
// }
// puts("");
// printf("%lld\n",sum);
// bug;
}
printf("%I64d\n",sum);
}
return 0;
}
2012/9/18更新:hdu上又遇到一题求逆序数的水题1A水过。
/*
Problem ID:
meaning:
Analyzing:
*/
#include <iostream>
#include <algorithm>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<vector>
using namespace std;
typedef struct even{int y1,y2,x;}even;
#define clr(A,k) memset(A,k,sizeof(A))
#define FOR(i,s,t) for(int i=(s); i<(t); i++)
#define LL long long
#define BUG puts("here!!!")
#define print(x) printf("%d\n",x)
#define STOP system("pause")
#define eps 1e-8
#define PI acos(-1.0)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define maxn 1006
#define lowbit(x) x&(-x)
LL gcd(LL a,LL b) {return a?gcd(b%a,a):b;}
int C[maxn],n;
int query(int x){
int ret=0;
x+=1;
while(x<=n){
ret+=C[x];
x+=lowbit(x);
}
return ret;
}
void update(int pos,int val){
while(pos>0){
C[pos]+=val;
pos-=lowbit(pos);
}
}
int main(){
while(~scanf("%d",&n)){
int ret=0,x;
clr(C,0);
for(int i=0;i<n;i++){
scanf("%d",&x);
update(x,1);
ret+=query(x);
}
print(ret);
}
return 0;
}