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
| void solve() { int n; cin >> n; vi a(n); vi ans(n + 1, INF); for (int i = 0; i < n; i++) { cin >> a[i]; ans[a[i]] = 1; }
sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end());
if (!a.empty() && a[0] == 1) { a.erase(a.begin()); } int pp = a.size();
queue<pii> q;
int cnt = 0;
for (int i = 0; i < pp; i++) q.emplace(make_pair(a[i], 1));
vi vis(n + 1);
while (!q.empty()) { auto hsh = q.front(); q.pop(); for (int i = 0; i < pp; i++) { if (a[i] * hsh.first <= n) { if (ans[a[i] * hsh.first] >= INF) { q.emplace(make_pair(a[i] * hsh.first, hsh.second + 1)); ans[a[i] * hsh.first] = hsh.second+1; } } else break; } }
for (int i = 1; i <= n; i++) { if (ans[i] > 3e8) cout << -1 << ' '; else cout << ans[i] << ' '; } cout << '\n'; }
|