公式
B - Intersection 解説
by
B - Intersection 解説
by
QCFium
\(A_i, B_i\) は \(1\) 以上 \(1000\) 以下なのであり得る \(x\) も \(1\) 以上 \(1000\) 以下です。
よって、それぞれの \(x\) について、実際に \(N\) 個の条件を満たすかをチェックすればよいです。
また別解として、\(x\) が満たす条件は \(\max(A_1, A_2, A_3, \dots, A_N) \le x\le \min(B_1, B_2, B_3, \dots, B_N)\) と言い換えられるので、答えは \(\max(0, \min(B_1, B_2, B_3, \dots, B_N) - \max(A_1, A_2, A_3, \dots, A_N) + 1)\) と求めることができます。
\(1\) つめの解法の計算量は \(\Theta (N \max{B_i})\) なのに対して、別解の計算量は \(\Theta(N)\) なのでより高速です。
解答例 (C)
#include <stdio.h>
#include <stdbool.h>
int ri() {
int n;
scanf("%d", &n);
return n;
}
int main() {
int n = ri();
int a[n];
for (int i = 0; i < n; i++) a[i] = ri();
int b[n];
for (int i = 0; i < n; i++) b[i] = ri();
int res = 0;
for (int i = 1; i <= 1000; i++) {
bool ok = true;
for (int j = 0; j < n; j++) if (i < a[j] || i > b[j]) ok = false;
if (ok) res++;
}
printf("%d\n", res);
return 0;
}
解答例 (Python)
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = 0
for i in range(1, 1001) :
ok = True
for j in range(n) :
if i < a[j] or i > b[j] : ok = False
if ok : res += 1
print(res)
投稿日時:
最終更新:
