Gym 102263 Problem - Meeting Bahosain
题目类型:数学、思维
题意
分别输入两个数组 a、b,每次可以选择 a 中的一个数然后减去 b 中的某一个数。判断最终是否可以将 a 中的值都变为相同的。
分析
建设修改 a 中的一个数 x,则修改后的结果为:
x - (k1 * b1 + b2 * b2 …… + kn * bn)
只考虑 k1*b1 产生的影响,则对 x 修改的值都为 b1 的倍数。
只考虑 k1b1 + k1b2产生的影响,则对 x 修改的值都为 gcd(b1, b2) 的倍数。
那么如果对于任意 (a[i] - a[i - 1]) % gcb(b) = 0) 成立的话则存在解,否则不可以。
具体细节可参考代码
代码
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static final int MAX_N = 1000010;
static final int mod = 1000000007;
static final int INF = 0x3f3f3f3f;
public static void main(String[] args) throws IOException {
initReader(System.in);
solve();
printWriter.flush();
}
/***********************************************************************************************************************/
static int[] a = new int[MAX_N];
static int[] b = new int[MAX_N];
public static void solve() throws IOException {
int n = nextInt();
int m = nextInt();
if (n == 1) {
printWriter.println("Yes");
return;
}
for (int i = 0; i < n; i++) a[i] = nextInt();
for (int i = 0; i < m; i++) {
b[i] = nextInt();
if (b[i] == 1) {
printWriter.println("Yes");
return;
}
}
boolean ok = true;
for (int i = 0; i < n; i++) {
if (a[0] != a[i]) {
ok = false;
break;
}
}
if (ok) {
printWriter.println("Yes");
return;
}
Arrays.sort(a, 0, n);
int g2;
if (m == 1) g2 = b[0];
else {
g2 = gcd(b[0], b[1]);
for (int i = 1; i <= m; i++) g2 = gcd(g2, b[i]);
}
boolean ans = true;
for (int i = 1; i < n; i++) {
if ((a[i] - a[i - 1]) % g2 != 0) {
ans = false;
break;
}
}
if (!ans) {
printWriter.println("No");
} else {
printWriter.println("Yes");
}
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
/***********************************************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter printWriter;
static void initReader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
static short nextShort() throws IOException {
return Short.parseShort(next());
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static char nextChar() throws IOException {
return next().charAt(0);
}
}