文章
454
粉丝
0
获赞
1
访问
10.0k
Aivan 在 b, b+a, b+2a… 尖叫,ZW 在 d, d+c, d+2c… 尖叫,求第一次同时尖叫的时刻,不存在则输出 -1。
即求最小的 t 使 t ≡ b (mod a) 且 t ≡ d (mod c),是标准同余方程组(CRT)。
数据很小(a、c ≤ 100),可以直接从 t = b 起按 lcm(a,c) 范围内枚举判断,找不到输出 -1。
注意同余要求 b、d 是时刻本身,枚举时跳过比 max(b,d) 小的值。
时间 O(lcm(a,c)),空间 O(1)。
C:
#include <stdio.h>
int main(void){long long a,b,c,d;
while(scanf("%lld %lld %lld %lld",&a,&b,&c,&d)==4){
int found=0;long long t;
for(int k=0;k<10000;k++){
t=b+(long long)k*a;
if(t>=d&&(t-d)%c==0){printf("%lld\n",t);found=1;break;}}
if(!found)printf("-1\n");}
return 0;}
C++:
#include <iostream>
using namespace std;
int main(){long long a,b,c,d;
while(cin>>a>>b>>c>>d){
bool found=false;
for(int k=0;k<10000;k++){
long long t=b+(long long)k*a;
if(t>=d&&(t-d)%c==0){cout<<t<<"\n";found=true;break;}}
if(!found)cout<<-1<<"\n";}
return 0;}
Java:
import java.io.*;
import java.util.*;
public class Main{
public ...
登录后发布评论
暂无评论,来抢沙发