3640. 素数子序列
DESCRIPTIONSTATISTICSDISCUSSION
Time limit per test: 1.0 seconds
Memory limit: 512 megabytes
有一个长度为 n 的序列 a1,a2,…,an,某些位置已经固定 (ai>0),其他位置允许乱填 (ai=0)。
现求一种填法,使得填完之后,序列的任意连续子序列的和都是质数。换句话说,对于一切 1≤l≤r≤n,al+al+1+⋯+ar 是质数。
Input
输入第一行一个整数 n (1≤n≤105)。
第二行 n 个整数用空格隔开 a1,a2,…,an (0≤ai≤109)。ai>0 表示该位置已经固定,ai=0 表示该位置可以乱填。
Output
输出 n 个整数,用空格隔开:a′1,a′2,…,a′n。填入的整数范围与输入相同,即 1≤a′i≤109。
如果有多解输出任意一解。如果无解输出 Impossible
。
Examples
input
3 2 0 2
output
2 3 2
input
5 2 3 3 3 3
output
Impossible
input
1 998244353
output
998244353
解法:三个数以上肯定不行。三个数只有2 3 2。两个数如果有一个为0,则另一个数判断是不是2,如果不是2 判断2和这个数能不能满足。如果是2 输出2 和 3即可。
判断素数的方法用了博客中的6的倍数附近的性质。代码重写了一遍elegant多了。
#include <bits/stdc++.h>
#define pii pair<int, int>
#define vi vector<int>
#define ll long long
#define eps 1e-3
using namespace std;
const int maxn = 2e5 + 10;
map<int, int> ind;
int a[maxn];
bool isprime(ll n)
{
if(n == 2 || n == 3 || n == 5)
return 1;
if(n == 1 || n == 0 || n == 4)
return 0;
if(n % 6 != 1 && n % 6 != 5)
return 0;
int temp = sqrt(n);
for(int i = 5; i <= temp; i += 6)
if(n % i == 0 || n % (i + 2) == 0)
return 0;
return 1;
}
int main()
{
//freopen("/Users/vector/Desktop/in", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
if(n == 1)
{
if(!a[0])
cout << 2 << endl;
else
{
if(isprime(a[0]))
cout << a[0] << endl;
else
cout << "Impossible" << endl;
}
}
else if(n == 2)
{
if(a[0] && a[1])//两个数均不为0
{
if(isprime(a[0]) && isprime(a[1]) && isprime(a[0] + a[1]))
cout << a[0] << ' ' << a[1] << endl;
else
cout << "Impossible" << endl;
}
else if(!(a[0] | a[1]))//两个数均为0
{
cout << "2 3" << endl;
}
else{
if(a[0] == 0)
{
if(a[1] == 2)
cout << "3 2" << endl;
else
{
if(isprime(a[1]) && isprime(a[1] + 2))
cout << 2 << ' ' << a[1] << endl;
else
cout << "Impossible" << endl;
}
}
else
{
if(a[0] == 2)
cout << "2 3" << endl;
else
{
if(isprime(a[0]) && isprime(a[0] + 2))
cout << a[0] << ' ' << 2 << endl;
else
cout << "Impossible" << endl;
}
}
}
}
else if(n == 3)
{
int p[] = {2, 3, 2};
bool f = 1;
for(int i = 0; i < n; i++)
if(a[i] != p[i] && a[i] != 0)
f = 0;
if(f)
cout << "2 3 2" << endl;
else
cout << "Impossible" << endl;
}
else
cout << "Impossible" << endl;
return 0;
}