---
id: 150
lang: en
translation_of: index.md
source_sha256: 30984f88858e00e85f22a16931fc8944f8c87bf14fee7ba83853910bb5e4a6af
title: "P1966: Lining Up Matches — Solution"
description: "Sort both sequences, map one onto the other by original index, and count the inversion pairs of that mapping with merge sort."
tags: ["OI","Inversion Pairs","Merge Sort"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 火柴排队 (literally “matches lining up”) rendered as “Lining Up Matches”."
---

## Approach

We first read $a,b$ into a data structure, and sort both sequences with the height as the key. Let's first write out what one sample looks like after sorting (the array subscripts are the original positions):
$$
\{1_3,2_1,3_2,4_4\}
$$
and
$$
\{1_3,2_2,3_1,4_4\}
$$
Looking at this, we notice that we can obviously discretize. So let $mapping[]$ be the discretized array; after sorting both groups, doing $mapping[a[i].index] = b[i].index$ completes the discretization. The problem then turns into how many transformations array b needs to become identical to a (since we have already discretized, $mapping[]$ can stay within the range of $n$). We can think of counting the number of inversion pairs to solve this. And the problem is solved with ease.

<!--more-->

## Code

```cpp
// P1966.cpp
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000200;
const int mod = 99999997;
#define ll long long
struct element
{
    int val, idx;
    bool operator<(const element &ele) const
    {
        return val < ele.val;
    }
} a[maxn], b[maxn];
int mapping[maxn], tmp[maxn], n;
int ans = 0;

void merge(int l, int mid, int r)
{
    int sa = l;
    int p = mid + 1;
    int bias = l;
    while (sa <= mid && p <= r)
        if (mapping[sa] < mapping[p])
            tmp[bias++] = mapping[sa++];
        else
            tmp[bias++] = mapping[p++], ans += (mid - sa + 1), ans %= mod;
    while (sa <= mid)
        tmp[bias++] = mapping[sa++];
    while (p <= r)
        tmp[bias++] = mapping[p++];
    for (int i = l; i <= r; i++)
        mapping[i] = tmp[i];
}

void mergeSort(int l, int r)
{
    if (l == r)
        return;
    int mid = (l + r) >> 1;
    mergeSort(l, mid);
    mergeSort(mid + 1, r);
    merge(l, mid, r);
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i].val), a[i].idx = i;
    for (int i = 1; i <= n; i++)
        scanf("%d", &b[i].val), b[i].idx = i;
    sort(a + 1, a + n + 1);
    sort(b + 1, b + n + 1);
    for (int i = 1; i <= n; i++)
        mapping[a[i].idx] = b[i].idx;
    mergeSort(1, n);
    cout << ans;
    return 0;
}
```
