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;
}