ABC186E

题目:

We have N chairs arranged in a circle, one of which is a throne.
Takahashi is initially sitting on the chair that is S chairs away from the throne in the clockwise direction. Now, he will repeat the move below.
Move: Go to the chair that is K chairs away from the chair he is currently sitting on in the clockwise direction.
After how many moves will he be sitting on the throne for the first time? If he is never going to sit on it, report -1 instead.
You are asked to solve T test cases.
1≤T≤100
2≤N≤1e9
1≤S<N
1≤K≤1e9

输入:

Input is given from Standard Input in the following format. The first line is in the format below:
T
Then, the following T lines represent T test cases. Each of these lines is in the format below:
N S K

输出:

For each test case, print the answer in its own line.

样例:

Sample Input 1

4
10 4 3
1000 11 2
998244353 897581057 595591169
10000 6 14

Sample Output 1

2
-1
249561088
3571

In the first test case, we have 10 chairs, and Takahashi is initially sitting on the chair that is 4 chairs away from the throne in the clockwise direction. He will be sitting on the throne after 2 moves of moving 3 chairs in the clockwise direction.
In the second test case, he will never sit on the throne, so we should print -1.

tag:

扩展欧几里得

题意:

有 N 个椅子围成一个圈,其中一个是王位。开始的时候,坐在离王位 S 的椅子上
他可以重复此操作:顺时针方向移动到距离自己k的椅子。
问,经过多少次移动,能第一次坐到王位。如果不可能,输出 -1。

思路:

设移动x次后,到达王座,此时一共转了y圈
要使得最后到达王座 那么有 (kx+s)%n=0,即求最小正整数解x
kx + ny = -s
由拓展欧几里得 d=exgcd(k,n,x,y)
如果 s%d!=0则无解 否则可得 x= (-x
s/d%t+t)%t其中t=n/d

代码

#include<bits/stdc++.h>
typedef long long ll; 
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y){
	if(b==0){
		x=1,y=0;
		return a;
	}
	ll d=exgcd(b,a%b,y,x);
	y=y-(a/b)*x;
	return d;
}
int main()
{
	int t;
	cin >> t;
	while(t--){
		ll n,s,k;
		cin >> n >> s >> k;
		ll x,y;
		ll d=exgcd(k,n,x,y);
		if(s%d){
			cout << -1 << endl;
		}
		else{
			ll t=n/d;
			cout << (-x*s/d%t+t)%t << endl;
		}
	} 
	return 0;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值