一、内容
You are given a positive integer m and two integer sequence: a=[a1,a2,…,an] and b=[b1,b2,…,bn]. Both of these sequence have a length nPermutation is a sequence of ndifferent positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [0], [1,1], [2,3]You need to find the non-negative integer x, and increase all elements of ai by x, modulo m (i.e. you want to change ai to (ai+x)modm), so it would be possible to rearrange elements of a to make it equal b, among them you need to find the smallest possible x.In other words, you need to find the smallest non-negative integer x, for which it is possible to find some permutation p=[p1,p2,…,pn], such that for all 1≤i≤n, (ai+x)modm=bpi, where ymodm — remainder of division of y by m.For example, if m=3, a=[0,0,2,1],b=[2,0,1,1], you can choose x=1, and a will be equal to [1,1,0,2] and you can rearrange it to make it equal [2,0,1,1], which is equal to b
.
Input
The first line contains two integers n,m(1≤n≤2000,1≤m≤109): number of elemens in arrays and mThe second line contains nintegers a1,a2,…,an (0≤ai<m).The third line contains nintegers b1,b2,…,bn (0≤bi<m).It is guaranteed that there exists some non-negative integer x, such that it would be possible to find some permutation p1,p2,…,pn such that (ai+x)modm=bpi
Output
Print one integer, the smallest non-negative integer x, such that it would be possible to find some permutation p1,p2,…,pn such that (ai+x)modm=bpi for all 1≤i≤n
Input
4 3
0 0 2 1
2 0 1 1
Output
1
二、思路
- 由于a数组中肯定一个数会与b数组中一个数配对,所以我们暴力枚举下所有情况即可。
三、代码
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 2005;
int n, m;
ll a[N], b[N], c[N], ans = 1e18;
bool ok() {
for (int i = 1; i <= n; i++) {
if (c[i] != b[i]) return false;
}
return true;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (int i = 1; i <= n; i++) scanf("%lld", &b[i]);
sort(b + 1, b + 1 + n);
for (int i = 1; i <= n; i++) {
ll x = a[1] <= b[i] ? (b[i] - a[1]) : (b[i] + m - a[1]);
for (int j = 1; j <= n; j++) {
c[j] = (a[j] + x) % m;
}
sort(c + 1, c + 1 + n);
if (ok()) ans = min(ans, x);
}
printf("%lld", ans);
return 0;
}