結果

問題 No.2119 一般化百五減算
ユーザー kiliarinkiliarin
提出日時 2022-11-04 22:30:59
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 22 ms / 2,000 ms
コード長 1,097 bytes
コンパイル時間 219 ms
コンパイル使用メモリ 33,720 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-26 01:01:37
合計ジャッジ時間 1,445 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,384 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 AC 1 ms
4,380 KB
testcase_11 AC 1 ms
4,376 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 2 ms
4,380 KB
testcase_15 AC 1 ms
4,376 KB
testcase_16 AC 1 ms
4,380 KB
testcase_17 AC 1 ms
4,376 KB
testcase_18 AC 1 ms
4,376 KB
testcase_19 AC 1 ms
4,376 KB
testcase_20 AC 16 ms
4,376 KB
testcase_21 AC 16 ms
4,380 KB
testcase_22 AC 22 ms
4,376 KB
testcase_23 AC 20 ms
4,376 KB
testcase_24 AC 21 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LOG(FMT...) fprintf(stderr, FMT)

const int N = 100005;

int n, m, b[N], c[N];

int exgcd(int a, int b, int &x, int &y) {
	if (b) {
		int d = exgcd(b, a % b, y, x);
		y -= a / b * x;
		return d;
	}
	x = y = 1;
	return a;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 0; i < m; ++i) {
		scanf("%d%d", b + i, c + i);
		c[i] %= b[i];
		if (c[i] < 0) {
			c[i] += b[i];
		}
	}
	int B, C;
	B = 1, C = 0;
	for (int i = 0; i < m; ++i) {
		if (b[i] > B) {
			B = b[i], C = c[i];
		}
	}
	for (int i = 0; i < m && B < 1000; ++i) {
		int x, y, d;
		d = exgcd(B, b[i], x, y);
		int dc = C - c[i];
		if (dc % d) {
			puts("NaN");
			return 0;
		}
		int t = dc / d;
		x *= t, y *= t;
		int nb = B * b[i] / d;
		int nc = (c[i] + y * b[i]) % nb;
		if (nc < 0) {
			nc += nb;
		}
		B = nb, C = nc;
	}
	for (int k = 0, x; (x = k * B + C) <= n; ++k) {
		bool flag = true;
		for (int i = 0; i < m; ++i) {
			if (x % b[i] != c[i]) {
				flag = false;
			}
		}
		if (flag) {
			printf("%d\n", x);
			return 0;
		}
	}
	puts("NaN");
	return 0;
}
0