# 洛谷 P1966 火柴排队 题解

## 输入输出样例

4
2 3 1 4
3 2 1 4


1

4
1 3 4 2
1 7 2 4

2

## 说明

【输入输出样例说明1】

【输入输出样例说明2】

【数据范围】

2017.11.8更新：补上归并排序的代码。

AC代码：

 1 #include<cstdio>
2 #include<algorithm>
3 #include<cmath>
4 #include<cstring>
5
6 const int MOD = 99999997;
7 const int MAXN = 100005;
8
10 {
11     char ch = getchar(),c = ch;x = 0;
12     while(ch < '0' || ch > '9') c = ch,ch = getchar();
13     while(ch <= '9' && ch >= '0') x = (x<<1)+(x<<3)+ch-'0',ch = getchar();
14     if(c == '-') x = -x;
15 }
16
17 int n,rank[MAXN];
18 long long ans;
19
20 struct NUM
21 {
22     int ord,v;
23 }a[MAXN],b[MAXN];
24
25 int cmp(NUM a,NUM b)
26 {return a.v < b.v;}
27
28 inline int lowbit(int x)
29 {return x&(-x);}
30
31 inline void update(int x,int num)
32 {
33     while(x <= n)
34     {
35         c[x] += num;
36         x += lowbit(x);
37     }
38 }
39
40 inline int sum(int x)
41 {
42     int sum = 0;
43     while(x > 0)
44     {
45         sum += c[x];
46         x -= lowbit(x);
47     }
48     return sum;
49 }
50 int main()
51 {
53     for(register int i = 1;i <= n;++ i)
55     for(register int i = 1;i <= n;++ i)
57     std::sort(a+1,a+1+n,cmp);
58     std::sort(b+1,b+1+n,cmp);
59     for(register int i = 1;i <= n;++ i)
60         rank[a[i].ord] = b[i].ord;
61     for(register int i = 1;i <= n;++ i)
62     {
63         update(rank[i],1);
64         ans = (ans + i - sum(rank[i]))%MOD;
65     }
66     printf("%lld\n",ans);
67     return 0;
68 }

 1 #include<cstdio>
2 #include<cmath>
3 #include<algorithm>
4 #include<cstring>
5
6 const int MAXN = 100002;
7 const int MOD = 99999997;
9 {
10     char ch = getchar(),c = ch;x = 0;
11     while(ch < '0' || ch > '9') c = ch,ch = getchar();
12     while(ch <= '9' && ch >= '0') x = (x<<1)+(x<<3)+ch-'0',ch = getchar();
13     if(c == '-') x = -x;
14 }
15
16 int n,c[MAXN],rank[MAXN];
17 long long ans;
18
19 struct NUM
20 {
21     int val,ord;
22 }a[MAXN],b[MAXN];
23
24 int cmp(NUM a,NUM b)
25 {return a.val < b.val;}
26
27 void merge(int l,int r)
28 {
29     if(l == r) return;
30     int mid = (l+r)>>1;
31     merge(l,mid);
32     merge(mid+1,r);
33
34     int tmp = l,i = l,j = mid+1;
35     for(;i<=mid && j<=r;)
36     {
37         if(rank[i] <= rank[j]) c[tmp++] = rank[i++];
38         else if(rank[i] > rank[j]) c[tmp++] = rank[j++],ans += (mid-i+1);
39     }
40     ans %= MOD;
41     for(;i<=mid;) c[tmp++] = rank[i++];
42     for(;j<=r;) c[tmp++] = rank[j++];
43
44     for(int x = l;x <= r;++ x)
45         rank[x] = c[x];
46 }
47
48 int main()
49 {
51     for(int i = 1;i <= n;++ i)
53     for(int i = 1;i <= n;++ i)
62 }