这题也是求逆序数,只是题目描述有点诡异==!给出的是钩子的id,不是一对一的关系,所以要映射一下,喜欢上用归并求逆序数
#define N 1010
int a[N],b[N];
int tmp[N];
int sum;
void merge_sort(int l,int mid,int r){
int i = l,j = mid+1,k = 1;
while(i<=mid && j<=r){
if(a[j]<a[i]){
tmp[k++] = a[j++];
sum += mid-i+1;
} else tmp[k++] = a[i++];
}
while(i<=mid)tmp[k++] = a[i++];
while(j<=r)tmp[k++] = a[j++];
for(i=l,k=1;i<=r;i++,k++){
a[i] = tmp[k];
}
}
void merge(int s,int t){
if(s==t)return ;
int mid = (s+t)>>1;
merge(s,mid);
merge(mid+1,t);
merge_sort(s,mid,t);
}
int main(){
int n;
while(scanf("%d",&n) != -1){
int i,j;
for(i=1;i<=n;i++){
scanf("%d%d",&a[i],&b[i]);
tmp[a[i]] = i;
}
for(i=1;i<=n;i++){
a[i] = tmp[b[i]];
}
sum = 0;
merge(1,n);
printf("%d\n",sum);
}
return 0;
}