Submission #236686

#TimeUsernameProblemLanguageResultExecution timeMemory
236686DS007Jakarta Skyscrapers (APIO15_skyscraper)C++14
100 / 100
300 ms131156 KiB
#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N = 30000;
vector<pair<int, int>> adj[N];
int b[N], p[N];
set<int> inv[N];
int n, m;

void solveTestCase() {
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        cin >> b[i] >> p[i];
        inv[b[i]].insert(p[i]);
    }

    for (int i = 0; i < n; i++) {
        for (int j : inv[i]) {
            for (int k = i - j, l = 1; k >= 0; k -= j, l++) {
                adj[i].emplace_back(k, l);
                if (inv[k].count(j))
                    break;
            }
            for (int k = i + j, l = 1; k < n; k += j, l++) {
                adj[i].emplace_back(k, l);
                if (inv[k].count(j))
                    break;
            }
        }
    }

    int dist[n];
    fill(dist, dist + n, 1e18);
    dist[b[0]] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(greater<>())> pq;
    pq.push({0, b[0]});
    set<int> done;

    while (!pq.empty()) {
        auto temp = pq.top();
        pq.pop();

        if (done.count(temp.second))
            continue;
        done.insert(temp.second);
        assert(temp.first == dist[temp.second] && temp.first != 1e18);

        for (auto i : adj[temp.second]) {
            if (dist[i.first] > temp.first + i.second) {
                dist[i.first] = temp.first + i.second;
                pq.push({dist[i.first], i.first});
            }
        }
    }

    cout << (dist[b[1]] == 1e18 ? -1 : dist[b[1]]);
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int test = 1;
    // cin >> test;
    while (test--)
        solveTestCase();
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...