• B.Modulo Equality


    题意:有两个整数序列a = [a1, a2, ..., an],b = [b1, b2, ..., bn],长度都为n,找到一个最小的数x,使得a的每个数增加x之后对m取模,然后重新排序序列a,使得a == b

    原题链接:Modulo Equality

    输入:n,m,序列长度和模数m,第二行是a1,a2,...,an,第三行是b1,b2,...,bn
    输出:最小的x

    分析:枚举x,导致时间复杂度很大,我在做的时候超时了...
    换一种思路,让时间复杂度降低,因为我们每个数字a加了一个数x后对m取模后都对应着0 ~ m - 1之间的数,我们可以枚举数字差,这样时间复杂度会大幅度降低,
    我们枚举序列a的每个数字,去对应序列b中的b[0],因为b[0]会对应序列a中的某个数字,我们枚举序列a,然后相减,对m取模,得到x,然后对序列a的每个数字增加x,
    排完序后,检查a == b是否相等,然后找到最小的x...

    代码如下:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    const int INF = 0x3f3f3f3f;
    
    int main()
    {
    	vector<int> a, b;
    	
    	int n, m;
    	scanf("%d%d", &n, &m);
    	a.resize(n), b.resize(n);
    	for (int i = 0; i < n; ++i)
    	{
    		scanf("%d", &a[i]);
    	}
    	for (int i = 0; i < n; ++i)
    	{
    		scanf("%d", &b[i]);
    	}
    	
    	sort(b.begin(), b.end());
    
    	int minx = INF;
    	for (int i = 0; i < n; ++i)
    	{
    		int x;
    		if (b[0] >= a[i])
    		{
    			x = b[0] - a[i];
    		}
    		else {
    			x = m + b[0] - a[i];
    		}
    
    		vector<int> c(a);
    		for (int j = 0; j < n; ++j) c[j] = (c[j] + x) % m;
    
    		sort(c.begin(), c.end());
    
    		if (c == b)
    		{
    			minx = min(minx, x);
    		}
    	}
    
    	printf("%d
    ", minx);
    	return 0;
    }
    
  • 相关阅读:
    pandas read_excel 产生 Unnamed:0 列
    python 打印输出百分比符号%
    python 内存回收
    python 编码问题
    python 判断 txt 编码方式
    python 二维list取列
    python 两个list 求交集,并集,差集
    pandas Timestamp的用法
    Dataframe 取列名
    Dataframe 新增一列, apply 通用方法
  • 原文地址:https://www.cnblogs.com/pixel-Teee/p/12088415.html
Copyright © 2020-2023  润新知