#include <bits/stdc++.h>
//#include "grader.h"
#define respagold ios_base::sync_with_stdio(0), cin.tie(0);
#define int long long
#define ll long long
#define int2 __int128_t
#define FOR( i, x, n, d ) for( int i = x; i <= n; i += d )
#define FORR( i, x, n, d ) for( int i = x; i >= n; i -= d )
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x.size())
#define pb push_back
#define ins insert
#define lb lower_bound
#define ub upper_bound
#define pii pair <int, int>
#define mkp make_pair
using namespace std;
const int N = 3e4 + 123;
const int inf = 1e18;
const int mod = 998244353;
int a[N], b[N], c[N], n, m, k, z, w, x, y, mm[N], cc[N];
bool used[N][175], used2[N];
vector <int> g[N];
mt19937 rng( chrono::steady_clock::now().time_since_epoch().count());
int rand( int l, int r )
{
uniform_int_distribution <int> uid( l, r );
return uid( rng );
}
int binpow( int a, int b )
{
if( !b ) return 1;
if( b & 1 ) return binpow( a, b - 1 ) * a % mod;
int res = binpow( a, b >> 1 ); return res * res % mod;
}
void solve()
{
cin >> n >> m;
k = sqrt(n);
FOR( i, 1, m, 1 ) cin >> a[i] >> b[i], a[i] ++, g[a[i]].pb(i);
FOR( i, 1, n, 1 ) c[i] = inf;
queue <pair <int, pii>> q;
q.push({ a[1], { 0, b[1] }});
while( !q.empty() )
{
pair <int, pii> v = q.front();
q.pop(); c[v.F] = min( c[v.F], v.S.F );
if( !used2[v.F] )
{
used2[v.F] = 1;
for( auto to : g[v.F] )
{
if( v.F - b[to] >= 1 ) q.push({ v.F - b[to], { v.S.F + 1, -b[to] }});
if( v.F + b[to] <= n ) q.push({ v.F + b[to], { v.S.F + 1, b[to] }});
}
}
if( abs(v.S.S) <= k )
{
if( used[v.F][abs(v.S.S)] ) continue;
used[v.F][abs(v.S.S)] = 1;
}
if( 1 <= v.F + v.S.S && v.F + v.S.S <= n ) q.push({ v.F + v.S.S, { v.S.F + 1, v.S.S }});
}
cout << ( c[a[2]] == inf ? -1 : c[a[2]] );
}
signed main()
{
// freopen("connect.in", "r", stdin);
// freopen("connect.out", "w", stdout);
respagold
int test = 1;
if( !test ) cin >> test;
while( test -- )
{
solve();
}
}
// solved by KluydQ
# | 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... |