构造题

比赛链接

牛客挑战赛57

A.构造题

题目描述

给定一个正整数序列 \(a_1\sim a_n\),你需要构造一个数列 \(b\) ,满足对于任何 \(i\)\(b_i=a_i\)\(b_i=a_i+1\),你需要最大化 \(\gcd(b_1,b_2\dots b_n)\),即 \(b\) 中所有数的最大公约数。

输入描述:

第一行一个正整数 \(n(1\leq n\leq 10^6)\)

第二行 \(n\) 个正整数 \(a_i (1\leq a_i\leq 10^6)\)

输出描述:

一行一个正整数,表示答案。

示例1

输入

5
2 9 6 11 3

输出

3

说明

构造 \(b_1=3,b_2=9,b_3=6,b_4=12,b_5=3\) 即可达到最大值。

示例2

输入

7
11 45 14 19 19 8 10

输出

2

解题思路

构造
结论:两个相邻的非零自然数互质

不妨从大到小枚举这个最大公约数,则原数列中的每一个数都为这个公约数的倍数或减一,统计每个数的出现次数,由于两个相邻的非零自然数互质,直接统计两种情况的出现次数,为 \(n\) 时说明满足要求

\(v\) 为值域,则:

  • 时间复杂度:\(O(vlogv+n)\)

代码

// Problem: 构造题
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/11197/A
// Memory Limit: 524288 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e6+5;
int n,a[N],v[N];
int main()
{
    int mx=0;
    cin>>n;
    for(int i=0;i<n;i++)
    {
    	int x;
    	cin>>x;
    	mx=max(mx,x);
    	v[x]++;
    }
    mx++;
    for(int i=mx;i;i--)
    {
    	int s=0;
    	for(int j=i;j<=mx;j+=i)s+=v[j]+v[j-1];
    	if(s==n)
    	{
    		cout<<i;
    		return 0;
    	}
    }
    return 0;
}
posted @ 2022-02-21 08:27  zyy2001  阅读(111)  评论(0编辑  收藏  举报