This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define pb push_back
#define all(x) begin(x), end(x)
#define SZ(x) (int)(x).size()
#define cps(x) sort(all(x)), (x).erase(unique(all(x)), end(x))
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int n0 = 2003, m0 = 2003;
const int k0 = n0 * m0;
int n, m, b[m0], p[m0], k, d[k0], inf, ind[n0][m0];
vector <int> g[n0];
int sz[k0];
array <int, 2> gr[k0][3];
void bfs(int x, int y) {
memset(& d, 0x3f, sizeof(d));
inf = d[0];
deque <int> q;
d[ind[x][y]] = 0;
q.push_front(ind[x][y]);
while (!q.empty()) {
int v = q.front();
q.pop_front();
if (v < n) {
for (int to : g[v]) {
if (d[to] > d[v]) {
d[to] = d[v];
q.push_front(to);
}
}
} else {
for (int i = 0; i < sz[v]; i++) {
int to = gr[v][i][0], w = gr[v][i][1];
if (d[to] > d[v] + w) {
d[to] = d[v] + w;
if (w == 0) q.push_front(to);
else q.pb(to);
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++)
cin >> b[i] >> p[i];
for (int i = 0; i < n; i++)
ind[i][m] = k++;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ind[i][j] = k++;
for (int i = 0; i < m; i++)
g[ind[b[i]][m]].pb(ind[b[i]][i]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if ((i % p[j]) != (b[j] % p[j])) continue;
int x = ind[i][j];
if (i - p[j] >= 0) gr[x][sz[x]++] = {ind[i - p[j]][j], 1};
if (i + p[j] < n) gr[x][sz[x]++] = {ind[i + p[j]][j], 1};
gr[x][sz[x]++] = {ind[i][m], 0};
}
}
bfs(b[0], 0);
int res = d[ind[b[1]][1]];
if (res == inf) res = -1;
cout << res;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |