有两个整数序列a = [a1, a2, ..., an],b = [b1, b2, ..., bn],长度都为n,找到一个最小的数x,使得a中的每个数加上x后对m取模,然后重新排序序列a,使得a = b。
Input
第一行为n,m (1≤n≤2000,1≤m≤10^9),分别是数组的大小和m。
第二行为数组a的所有元素(0≤ai<m ).
第二行为数组b的所有元素 (0≤bi<m ).
It is guaranteed that there exists some non-negative integer xx , such that it would be possible to find some permutation p1,p2,…,pnp1,p2,…,pn such that (ai+x)modm=bpi(ai+x)modm=bpi .
Output
输出可以加上满足(ai+x) mod m=b 的最小x 。
Input
4 3
0 0 2 1
2 0 1 1
Output
1
Input
3 2
0 0 0
1 1 1
Output
1
Input
5 10
0 0 0 1 2
2 1 0 0 0
Output
0
由于a数组中肯定一个数会与b数组中一个数配对,所以我们暴力枚举x,直至找到满足条件的x。
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2005;
int n, m;
ll a[maxn],b[maxn],c[maxn];
bool ok()
{
for (int i = 1; i <= n; i++)
{
if (c[i] != b[i])
return 0;
}
return 1;
}
int main()
{
ll ans=0x3f3f3f3f;
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;
}