Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1)B. Primal Sport
Alice and Bob begin their day with a quick game. They first choose a starting number?X0?≥?3?and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the?i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime?p?<?Xi?-?1?and then finds the minimum?Xi?≥?Xi?-?1?such that?p?divides?Xi. Note that if the selected prime?p?already divides?Xi?-?1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given?X2, help her determine what is the smallest possible starting number?X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
InputThe input contains a single integer?X2?(4?≤?X2?≤?106). It is guaranteed that the integer?X2?is composite, that is, is not prime.
OutputOutput a single integer?— the minimum possible?X0.
Examples input 14 output 6 input 20 output 15 input 8192 output 8191 NoteIn the first test, the smallest possible starting number is?X0?=?6. One possible course of the game is as follows:
- Alice picks prime 5 and announces?X1?=?10
- Bob picks prime 7 and announces?X2?=?14.
In the second case, let?X0?=?15.
- Alice picks prime 2 and announces?X1?=?16
- Bob picks prime 5 and announces?X2?=?20.
題意:給定一個當前數xn,選擇一個比xn小的素數,然后取這個素數的倍數中比xn大的最小的數作為xn+1;輸入一個x2,輸出x0最小的可能解。
時間復雜度O(n*sqrt(n))的解法:
容易得到,對于每一個xn,假設它的一個質因數為p,那么xn-1的取值范圍是((xn/p - 1) * p, xn];那么顯然對于這個數所有的質因數,小的質因數對應的域是屬于大的質因數對應的域的。所以對于輸入x2,求解其最大的質因數可以直接對應得到x1的取值范圍。
由先前證明已經得到,xn所對應的最小的xn-1的值是確定的,即(xn/p - 1) * p + 1,因此預處理素數和將該式的值,對所有得到的取值范圍內的x1按該值從小到大排序,輸出最小的那個值即可。
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <string> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #define INF 0x3f3f3f3f #define lowbit(x) (x&(-x)) #define eps 0.00000001 #define pn printf("\n") using namespace std; typedef long long ll;const int maxn = 1e6+1; int isp[maxn]; struct num {int k, p, maxp;int vis;bool operator <(const num &c) const {return p < c.p;} }n[maxn];void init() {for(int i=0;i<maxn;i++){n[i].k = i;n[i].p = i;n[i].vis = 0;n[i].maxp = 1;}for(int i=2;i<maxn;i++)if(!isp[i]){n[i].maxp = i;for(int j=i+i;j<maxn;j+=i){isp[j] = 1;n[j].maxp = i;n[j].p = min(n[j].p, (n[j].k/i - 1)*i + 1);}} }int main() {init();int x;scanf("%d",&x);int p2 = n[x].maxp;if(x / p2 < 2) printf("%d\n", x);else{int s = (x / p2 - 1) * p2 + 1;sort(n+s, n+x+1);printf("%d\n", n[s].p);}}?
轉載于:https://www.cnblogs.com/HazelNut/p/8612940.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1)B. Primal Sport的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 [P1352] 没有上司的舞会
- 下一篇: Win7搭建FTP服务器