Gibe in cpp
Creato il: 12 luglio 2025
Creato il: 12 luglio 2025
Here’s a straightforward O(N × log N) solution that scans every station once, checks whether its digits are type-able with the working keys, and keeps the best answer.
cpp#include <bits/stdc++.h> using namespace std; /* ---------- helpers ---------- */ int ringDist(int a, int b, int n) { // shortest F/B distance on a ring int forward = (b - a + n) % n; // move with F int backward = (a - b + n) % n; // move with B return min(forward, backward); } bool canType(int x, const vector<bool>& ok) { // all digits work? if (x == 0) return ok[0]; while (x) { if (!ok[x % 10]) return false; x /= 10; } return true; } int digitCount(int x) { // #digits in x (x ≥ 0) if (x == 0) return 1; int c = 0; while (x) { ++c; x /= 10; } return c; } /* ---------- core ---------- */ int leastBouttonPress(int n, int d, int digits[], int pres, int dest) { vector<bool> ok(10, false); for (int i = 0; i < d; ++i) ok[digits[i]] = true; int best = ringDist(pres, dest, n); // only F/B keys for (int s = 1; s <= n; ++s) { // try every type-able station if (!canType(s, ok)) continue; int cost = digitCount(s) + 1 // press digits of s, then Enter + ringDist(s, dest, n); // finish with F/B to dest best = min(best, cost); } return best; } /* ---------- driver ---------- */ int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, d, pres, dest; if (!(cin >> n)) return 0; cin >> d; vector<int> digs(d); for (int &x : digs) cin >> x; cin >> pres >> dest; cout << leastBouttonPress(n, d, digs.data(), pres, dest); return 0; }
Why it works
ringDist
handles the circular track (forward vs. backward moves).canType
checks if a station’s digits are all among the functioning keys.digits of s + 1 (Enter) + ringDist(s, dest)
.With N ≤ 10 000
, this runs easily within limits.