[暑假集训--数论]poj2657 Comfort

Description

A game-board consists of N fields placed around a circle. Fields are successively numbered from1 to N clockwise. In some fields there may be obstacles.

Player starts on a field marked with number 1. His goal is to reach a given field marked with number Z. The only way of moving is a clockwise jump of length K. The only restriction is that the fields the player may jump to should not contain any obstacle.

For example, if N = 13, K = 3 and Z = 9, the player can jump across the fields 1, 4, 7, 10, 13, 3, 6 and 9, reaching his goal under condition that none of these fields is occupied by an obstacle.

Your task is to write a program that finds the smallest possible number K.

Input

First line of the input consists of integers N, Z and M, 2 <= N <= 1000, 2 <= Z <= N, 0 <= M <= N - 2. N represents number of fields on the game-board and Z is a given goal-field.

Next line consists of M different integers that represent marks of fields having an obstacle. It is confirmed that fields marked 1 and Z do not contain an obstacle.

Output

Output a line contains the requested number K described above.

Sample Input

9 7 2
2 3

Sample Output

3

问在长度为n的环上走,每一次走k步,最后要走到z。有m个点是不可走的,问最小的k是多少

用exgcd可以解方程ax==b(mod c),把这个式子写成ax-cy==b,exgcd解出ax+cy==gcd(a,c),然后调一下系数,就能知道最小的x。

如果0到z-1的步数大于了0到某一个障碍位置的步数,说明先到障碍位置,就不行

 1 #include<cstdio>
 2 #include<iostream>
 3 #define LL long long
 4 using namespace std;
 5 inline LL read()
 6 {
 7     LL x=0,f=1;char ch=getchar();
 8     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
 9     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
10     return x*f;
11 }
12 int n,z,m;
13 int b[100010];
14 inline int exgcd(int a,int b,int &x,int &y)
15 {
16     if (!b){x=1;y=0;return a;}
17     int gcd=exgcd(b,a%b,x,y);
18     int t=x;x=y;y=t-a/b*y;
19     return gcd;
20 }
21 inline int calc(int a,int b,int c)//a*x==b(mod c)
22 {
23     int x=0,y=0;
24     int tt=exgcd(a,c,x,y);
25     if (b%tt!=0)return -1;x=(x*b/tt)%c;
26     int ss=c/tt;
27     x=(x%ss+ss)%ss;
28     return x;
29 }
30 int main()
31 {
32     while (~scanf("%d%d%d",&n,&z,&m))
33     {
34         z--;
35         for(int i=1;i<=m;i++)
36             b[i]=read()-1;
37         for (int i=1;i<=z;i++)
38         {
39             bool ok=1;
40             int step=calc(i,z,n);
41             if (step==-1)continue;
42             for (int j=1;j<=m;j++)
43             {
44                 int now=calc(i,b[j],n);
45                 if (now==-1||now>step)continue;
46                 ok=0;break;
47             }
48             if (ok){printf("%d
",i);break;}
49         }
50     }
51 }
poj 2657
原文地址:https://www.cnblogs.com/zhber/p/7284783.html