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;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pair<int,int>> vpi;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
#define pb push_back
#define rsz resize
#define sz(x) int(x.size())
#define all(x) begin(x), end(x)
#define f first
#define s second
int N,M;
int const m=3e4, n=3e4;
int B[m];
int P[m];
vi sky[n];
int dist[m];
priority_queue<pii>q;
bitset<n> vis;
bitset<m> pro;
int sqrtN = sqrt(N);
void activate(int loc, map<int,int> &adjnow)
{
int newloc;
trav(now, sky[loc])
{
if(P[now]>sqrtN)
{
for(int i=1; loc+i*P[now]<N; ++i)
{
newloc = loc+i*P[now];
if(vis[newloc])continue;
if(!sky[newloc].empty())
{
if(adjnow.find(newloc)!=adjnow.end())
{
adjnow[newloc] = min(adjnow[newloc], i);
}
else adjnow.insert({newloc, i});
}
}
for(int i=-1; loc+i*P[now]>=0; --i)
{
newloc = loc+i*P[now];
if(vis[newloc])continue;
if(!sky[newloc].empty())
{
if(adjnow.find(newloc)!=adjnow.end())
{
adjnow[newloc] = min(adjnow[newloc], -i);
}
else adjnow.insert({newloc, -i});
}
}
}
else
{
newloc = loc+P[now];
if(!vis[newloc]&&loc+P[now]<N)
{
sky[newloc].pb(P[now]);
if(adjnow.find(newloc)!=adjnow.end())
{
adjnow[newloc] = min(adjnow[newloc], 1);
}
else adjnow.insert({newloc, 1});
}
newloc = loc-P[now];
if(!vis[newloc]&&loc+P[now]<N)
{
sky[newloc].pb(P[now]);
if(adjnow.find(newloc)!=adjnow.end())
{
adjnow[newloc] = min(adjnow[newloc], 1);
}
else adjnow.insert({newloc, 1});
}
}
}
}
void dij(int x)
{
dist[x]=0;
q.push({0,x});
int b,w;
map<int,int> adjnow;
while(!q.empty())
{
int a = q.top().s;
q.pop();
if(vis[a])continue;
vis[a]=1;
if(a==B[1])return;
adjnow.clear();
activate(a, adjnow);
trav(e, adjnow)
{
b=e.f;
w=e.s;
if(dist[a]+w<dist[b])
{
dist[b]=dist[a]+w;
q.push({-dist[b],b});
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>N>>M;
F0R(i,M)
{
cin>>B[i]>>P[i];
sky[B[i]].pb(i);
}
int INF=1e9;
F0R(loc,N)
{
dist[loc]=INF;
}
dij(B[0]);
if(dist[B[1]]==INF)cout<<-1<<'\n';
else cout<<dist[B[1]]<<'\n';
return 0;
}
# | 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... |