印尼首都雅加达市有 N 座摩天楼外,雅加达市没有其他摩天楼。

有 Pi>0)。

在一次跳跃中,位于摩天楼 0≤b+p<N)的摩天楼。

编号为 1 的 doge。任何一个收到消息的 doge 有以下两个选择:

  1. 跳跃到其他摩天楼上;
  2. 将消息传递给它当前所在的摩天楼上的其他 doge。

请帮助 doge 们计算将消息从 1 号 doge。

输入格式

输入的第一行包含两个整数 M。

接下来 Pi。

输出格式

输出一行,表示所需要的最少步数。如果消息永远无法传递到 −1。

样例一

input

5 3
0 2
1 1
4 1

output

5

explanation

下面是一种步数为 5 的解决方案:

  • 2 步)。
  • 2 号 doge。
  • 3 步)。
  • 1 号 doge。

子任务

所有数据都保证 0≤Bi<N。

  • 子任务 1 (10 分)
    • 1≤N≤10
    • 1≤Pi≤10
    • 2≤M≤3
  • 子任务 2 (12 分)
    • 1≤N≤100
    • 1≤Pi≤100
    • 2≤M≤2000
  • 子任务 3 (14 分)
    • 1≤N≤2000
    • 1≤Pi≤2000
    • 2≤M≤2000
  • 子任务 4 (21 分)
    • 1≤N≤2000
    • 1≤Pi≤2000
    • 2≤M≤30000
  • 子任务 5 (43 分)
    • 1≤N≤30000
    • 1≤Pi≤30000
    • 2≤M≤30000

时间限制1s

空间限制MB

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#define maxn 30010
using namespace std;
int B,num,tot,s,t,head[maxn*110],m,n,vis[maxn*110],d[maxn*110],pos[110][maxn];
struct node{int b,p;}a[maxn];
struct Node{int to,pre,v;}e[maxn*500];
void Insert(int from,int to,int v){
    e[++num].to=to;
    e[num].v=v;
    e[num].pre=head[from];
    head[from]=num;
}
queue<int>q;
void spfa(){
    for(int i=0;i<=tot;i++)d[i]=1e9,vis[i]=0;
    q.push(a[0].b);
    d[a[0].b]=0;vis[a[0].b]=1;
    while(!q.empty()){
        int x=q.front();q.pop();vis[x]=0;
        for(int i=head[x];i;i=e[i].pre){
            int to=e[i].to;
            if(d[to]>d[x]+e[i].v){
                d[to]=d[x]+e[i].v;
                if(!vis[to])q.push(to),vis[to]=1;
            }
        }
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=0;i<m;i++)scanf("%d%d",&a[i].b,&a[i].p);
    tot=n-1;
    B=min(100,(int)sqrt(n));
    for(int i=1;i<=B;i++)
    for(int j=0;j<i;j++)
    for(int k=j;k<n;k+=i){
        pos[i][k]=++tot;
        Insert(tot,k,0);
        if(k>=i){
            Insert(tot,tot-1,1);
            Insert(tot-1,tot,1);
        }
    }
    for(int i=0;i<m;i++){
        if(a[i].p<=B)
            Insert(a[i].b,pos[a[i].p][a[i].b],0);
        else {
            for(int j=1;;j++)
                if(j*a[i].p+a[i].b>=n)break;
                else Insert(a[i].b,j*a[i].p+a[i].b,j);
            for(int j=1;;j++)
                if(a[i].b-j*a[i].p<0)break;
                else Insert(a[i].b,a[i].b-j*a[i].p,j);
        }
    }
    spfa();
    if(d[a[1].b]==1e9)puts("-1");
    else printf("%d\n",d[a[1].b]);
    return 0;
}

 

相关文章:

  • 2021-07-10
  • 2021-12-07
  • 2022-03-08
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
  • 2021-06-03
  • 2021-09-25
猜你喜欢
  • 2021-08-30
  • 2021-11-21
  • 2021-05-22
  • 2021-12-29
  • 2021-12-10
  • 2021-12-11
  • 2022-12-23
相关资源
相似解决方案