#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef unsigned long long l; typedef vector<l> v_l; typedef vector<v_l> vv_l; vv_l P; l find_best(l m, l n, v_l::iterator p_begin, v_l::iterator p_end){ l best = m; l p = *p_begin; if (p_begin + 1 == p_end){ return *(upper_bound(P[p].begin(), P[p].end(), n/m)-1) * m; } else{ for(;m<n;m*=p){ best = max(find_best(m, n, p_begin + 1, p_end), best); } } return best; } l brute_force(l k, l N, v_l p){ l temp, min_rem, n; for(temp=N;;){ n = temp; min_rem = 100; for(int i=0;i<k;){ int rem = n % p[i]; if(rem == 0){ n /= p[i]; continue; } if(rem < min_rem){ min_rem = rem; } i++; if(n == 1){ return temp; } } temp -= min_rem; } } int main(){ l k, N; v_l p; cin >> k >> N; l temp; for(int i=0;i<k;i++){ cin>>temp; p.push_back(temp); } // ALG for(int i=0;i<100;i++){ v_l temp; P.push_back(temp); } for(int i=0;i<k;i++){ l s = 1; l pp = p[i]; P[pp].push_back(s); for(;pp <= N/s;s *= pp){ P[pp].push_back(s); } P[pp].push_back(s); } if (k > 22) cout<<brute_force(k, N, p); else cout<<find_best(1, N, p.begin(), p.end())<<endl; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #include <iostream> #include <vector> #include <algorithm> using namespace std; typedef unsigned long long l; typedef vector<l> v_l; typedef vector<v_l> vv_l; vv_l P; l find_best(l m, l n, v_l::iterator p_begin, v_l::iterator p_end){ l best = m; l p = *p_begin; if (p_begin + 1 == p_end){ return *(upper_bound(P[p].begin(), P[p].end(), n/m)-1) * m; } else{ for(;m<n;m*=p){ best = max(find_best(m, n, p_begin + 1, p_end), best); } } return best; } l brute_force(l k, l N, v_l p){ l temp, min_rem, n; for(temp=N;;){ n = temp; min_rem = 100; for(int i=0;i<k;){ int rem = n % p[i]; if(rem == 0){ n /= p[i]; continue; } if(rem < min_rem){ min_rem = rem; } i++; if(n == 1){ return temp; } } temp -= min_rem; } } int main(){ l k, N; v_l p; cin >> k >> N; l temp; for(int i=0;i<k;i++){ cin>>temp; p.push_back(temp); } // ALG for(int i=0;i<100;i++){ v_l temp; P.push_back(temp); } for(int i=0;i<k;i++){ l s = 1; l pp = p[i]; P[pp].push_back(s); for(;pp <= N/s;s *= pp){ P[pp].push_back(s); } P[pp].push_back(s); } if (k > 22) cout<<brute_force(k, N, p); else cout<<find_best(1, N, p.begin(), p.end())<<endl; return 0; } |