Codeforces Round #609 (Div. 2) B. Modulo Equality

Codeforces Round #609 (Div. 2) B. Modulo Equality

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.

Input

The first line contains two integers n,m (1≤n≤2000,1≤m≤109): number of elemens in arrays and m.

The second line contains n integers a1,a2,…,an (0≤ai

The third line contains n integers b1,b2,…,bn (0≤bi

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.

Examples

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

昨晚一场痛苦的掉分局,被人hack了……,起因在于自己手贱,这道题基本思路我觉得就是排序加暴力,因为数组元素个数不多,一开始想先计算一下两列数的差ans,若不为固定值,暴力判断即可;若都为一个固定值就直接输出,结果问题就出在这里,当ans大于等于0时直接输出,小于0时我想的是输出m+ans,然后有个人想了一组这个:

2 10
4 9
1 6

按我的思路就是输出7,答案是2,太坑了/(ㄒoㄒ)/~~,赛后去掉就过了,emmm,有趣的div2……

#include
using namespace std;
typedef long long ll;

int main()
{
	ll a[2005],b[2005];
	map<ll,ll>m1,m2;
	ll n,m;
	cin>>n>>m;
	for(ll i=0;i<n;i++){cin>>a[i];
	m1[a[i]]++;}
	sort(a,a+n);
	for(ll i=0;i<n;i++)cin>>b[i];
    sort(b,b+n);
    ll ans=b[0]-a[0],cnt=0;
    for(ll i=0;i<n;i++){
        if(b[i]-a[i]==ans) cnt++;
    }
    if(cnt==n && ans>=0) cout<<ans;
    else{
        ans=1e9;
        for(ll i=0;i<n;i++){
            if(b[i]==b[0]) {m2[m+b[0]]++;}
        }
        for(ll i=0;i<n;i++){
            if(m1[a[i]]==m2[m+b[0]]){
                ll c[2005];
                for(ll j=0;j<n;j++){
                    c[j]=(a[j]+b[0]+m-a[i])%m;
                }
                sort(c,c+n);
                ll cnt=0;
                for(ll j=0;j<n;j++){
                    if(b[j]==c[j]) cnt++;
                }
                if(cnt==n) ans=min(ans,b[0]+m-a[i]);
            }
        }
        cout<<ans;
    }
  return 0;
}

你可能感兴趣的:(Codeforces,暴力,排序)