E1. Divisible Numbers (easy version)
E1. Divisible Numbers (easy version)
This is an easy version of the problem. The only difference between an easy and a hard version is the constraints on $a, b, c$ and $d$.
You are given $4$ positive integers $a, b, c, d$ with $a<c$ and $b<d$. Find any pair of numbers $x$ and $y$ that satisfies the following conditions:
- $a < x \leq c$ , $b < y \leq d$,
- $x \cdot y$ is divisible by $a \cdot b$.
Note that required $x$ and $y$ may not exist.
Input
The first line of the input contains a single integer $t$ $(1 \leq t \leq 10)$, the number of test cases.
The descriptions of the test cases follow.
The only line of each test case contains four integers $a, b, c$ and $d$ $(1 \leq a< c \leq {10}^{5}, 1 \leq b < d \leq {10}^{5})$.
Output
For each test case print a pair of numbers $a < x \leq c$ and $b < y \leq d$ such that $x \cdot y$ is divisible by $a \cdot b$. If there are multiple answers, print any of them. If there is no such pair of numbers, then print $\text{-1 -1}$.
Example
input
5 1 1 2 2 3 4 5 7 8 9 15 18 12 21 14 24 36 60 48 66
output
2 2 4 6 12 12 -1 -1 -1 -1
解题思路
容易想到的暴力做法是双重循环枚举$x$和$y$,这样做肯定会超时,因此可以想一下能否只枚举$x$,$y$则根据$ab \mid xy$这个条件直接求出来。
因为$xy$被$ab$整除,因此$y$必然被$\frac{a \cdot b}{\gcd(a \cdot b, x)}$整除。令$t = \frac{a \cdot b}{\gcd(a \cdot b, x)}$,因此当我们枚举到某个$x$,看一下在区间$[b+1, d]$内是否存在一个$t$的倍数,设这个数为$y$,如果存在则表示$x, y$就是一组解。
如何判断在$[b+1, d]$内是否存在一个$t$的倍数呢?只要看一下严格大于$b$的最小的$t$的倍数是否不超过$d$就可以了。
- 如果$t \mid b$,那么很明显严格大于$b$的最小的$t$的倍数是$(\frac{b}{t} + 1) \times t$。
- 如果$t \nmid b$,那么严格大于$b$的最小的$t$的倍数是$\left\lceil {\frac{b}{t}} \right\rceil \times t$。
因此可以统一表示成$\left( {\left\lfloor {\frac{b}{t}} \right\rfloor + 1} \right) \times t$。
AC代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef long long LL; 5 6 int gcd(LL a, LL b) { 7 return b ? gcd(b, a % b) : a; 8 } 9 10 void solve() { 11 int a, b, c, d; 12 cin >> a >> b >> c >> d; 13 LL k = 1ll * a * b; 14 for (int i = a + 1; i <= c; i++) { // 枚举x 15 LL t = k / gcd(k, i); // t|y,t是y的因子 16 if ((b / t + 1) * t <= d) { // 大于b的最小的t的倍数不超过d 17 printf("%d %d\n", i, d / t * t); 18 return; 19 } 20 } 21 printf("-1 -1\n"); 22 } 23 24 int main() { 25 int t; 26 scanf("%d", &t); 27 while (t--) { 28 solve(); 29 } 30 31 return 0; 32 }
参考资料
Codeforces Round #828 (Div. 3) Editorial:https://codeforces.com/blog/entry/108101
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/16807496.html