Intersections Gym - 101853C(逆序对模板)(归并排序)
In this problem, you are given two permutations a and b of n numbers, and you need to play a game with them! In this game, you are required to perform the following steps:
- For each number x, draw a line segment connecting between its positions in the given permutations.
- Count the number of intersections between the line segments.
For example, let us consider two permutations (5, 4, 2, 1, 3) and (2, 5, 4, 1, 3). The following picture shows the permutations after drawing all line segments. In the picture, the number of intersections between the line segments is 2.
Given the permutations a and b, your task is to play the game and to count number of intersections between the line segments. Can you?
Input
The first line contains an integer T (1 ≤ T ≤ 100), in which T is the number of test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 105), in which n is the size of permutations.
Then a line follow containing n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n), giving the first permutation a.
Then a line follow containing n distinct integers b1, b2, ..., bn (1 ≤ bi ≤ n), giving the second permutation b.
The sum of n overall test cases does not exceed 7 × 105.
Output
For each test case, print a single line containing the number of intersections between the line segments.
题意:1-n的两个排列分别在两行上,相同的数连线求线的交点数
思路:哈希思想桶标记每个数在第一行的位置输入第二行时把每个位置上的数改为在第一行的位置
代码:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cstdio>
#include <string>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
//#include <unordered_map>
#define Fbo friend bool operator < (node a, node b)
#define mem(a, b) memset(a, b, sizeof(a))
#define FOR(a, b, c) for (int a = b; a <= c; a++)
#define RFOR(a, b, c) for (int a = b; a >= c; a--)
#define off ios::sync_with_stdio(0)
#define sc(a) scanf("%d",&a)
bool check1(int a) { return (a & (a - 1)) == 0 ? true : false; }
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int Maxn = 2e5+9;
const double pi = acos(-1.0);
const double eps = 1e-8;
int a[Maxn], c[Maxn];
int mp[Maxn];
ll ans;//逆序对数量
void msort(int l, int r){
if (l == r)return;
int mid = (l + r) >> 1;
msort(l, mid); msort(mid + 1, r);
int i = l, j = mid + 1, k = l;
while (i <= mid && j <= r) {
if (a[i] <= a[j])
c[k++] = a[i++];
else {
c[k++] = a[j++];
ans += (mid - i + 1);
}
}
while (i <= mid)c[k++] = a[i++];
while (j <= r)c[k++] = a[j++];
for (i = l; i <= r; i++)
a[i] = c[i];
}
int main() {
off;
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
FOR(i, 1, n) {
int t;
cin >> t;
mp[t] = i;
}
FOR(i, 1, n) {
int t;
cin >> t;
a[i] = mp[t];
}
ans = 0;
msort(1, n);
cout << ans << endl;
}
}

浙公网安备 33010602011771号