Codeforces Round #609 (Div. 2) B. Modulo Equality 链接: 题意: 思路: 代码:

Codeforces Round #609 (Div. 2) B. Modulo Equality
链接:
题意:
思路:
代码:

https://codeforces.com/contest/1269/problem/B

题意:

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 n.

Permutation is a sequence of n different 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.

思路:

科研先考虑枚举x,但是x很大,同时根据题目可以保证每种数字只会对应一种数字,所以可以枚举数字差,再遍历一边检测。

代码:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e3+10;

int a[MAXN], b[MAXN];
int n, m;
map<int, int> Mp1, Mp2;

bool Check(int x)
{
    for (auto p: Mp1)
    {
        int newv = (p.first+x)%m;
        if (Mp2[newv] != p.second)
            return false;
    }
    return true;
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1;i <= n;i++)
    {
        scanf("%d", &a[i]);
        Mp1[a[i]]++;
    }
    for (int i = 1;i <= n;i++)
    {
        scanf("%d", &b[i]);
        Mp2[b[i]]++;
    }
    int ans = m;
    auto now = Mp1.begin()->first;
    for (auto p: Mp2)
    {
        int x;
        if (p.first >= now)
            x = p.first-now;
        else
            x = (m-now+p.first);
        if (Check(x))
            ans = min(ans, x);
    }
    printf("%d
", ans);

    return 0;
}