| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
归并排序求逆序对数最令人费解的是题意。
先按照a_i构造一个映射表: map[a_i] = i
再根据b_i取出映射到待排序的数组: c_i = map[b_i]
然后对c数组求逆序对数即可,我的方法是简单的归并排序
代码
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1005;
int n, ans = 0, a[N], c[N];
pair<int, int> b[N];
inline void mergeSort(int l, int r) {
if (l == r)return;
int mid = (l + r) >> 1;
mergeSort(l, mid);
mergeSort(mid + 1, r);
int i = l, j = mid + 1, tot = 0;
while (i <= mid&&j <= r) {
if (a[i] < a[j])c[++tot] = a[i++];
else ans += mid - i + 1, c[++tot] = a[j++];
}
while (i <= mid)c[++tot] = a[i++];
while (j <= r)c[++tot] = a[j++];
for (int t = 0; t < tot; t++)
a[l + t] = c[1 + t];
}
signed main(void) {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d%d", &b[i].first, &b[i].second);
for (int i = 1; i <= n; i++)
c[b[i].first] = i;
for (int i = 1; i <= n; i++)
a[i] = c[b[i].second];
mergeSort(1, n);
printf("%d\n", ans);
system("pause");
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator