2018湘潭邀請賽K題題解
K. 2018
Given a, b, c, d, find out the number of pairs of integers (x, y) where a x b, c y d and x y is a multiple of 2018.
Input
The input consists of several test cases and is terminated by end-of-file. Each test case contains four integers a, b, c, d.
Output
For each test case, print an integer which denotes the result.
Constraint
• 1 a b 109, 1 c d 109
• The number of tests cases does not exceed 104.
Sample Input
1 2 1 2018
1 2018 1 2018
1 1000000000 1 1000000000
Sample Output
3
6051
1485883320325200
題解:
這道題的思路雖說很簡單就是找在兩個範圍中分別取兩個點並使他們的積是2018的倍數,重要的是要理解最後消去重複點的方法。
我們可以通過題目知道只要尋找兩個範圍中1009和2018的個數了,因爲2018的約數只有1,2,1009,2018。一個範圍中1009的個數乘以另一個範圍中偶數的個數即是一部分2018的倍數的個數,還有種情況是一個範圍中2018的個數乘以另一個範圍中數字的個數即使一部分2018的倍數的個數,用同樣的方法求另一個範圍中的2018的倍數然後再加起來。
這樣算出來可能有重複解,1009×2018,2018×2018,2018×1009.
AC代碼:
#include <stdio.h>
#include <string.h>
long long fw(int x, int y) {
if(x%2 != 0 && y%2 != 0) {
return (y-x)/2;
} else if(x%2 == 0 && y%2 == 0) {
return ((y-x)/2)+1;
} else {
return (y-x+1)/2;
}
}
int main() {
long long a, b, c, d;
while(scanf("%lld%lld%lld%lld", &a, &b, &c, &d) != EOF) {
long long f1, f2;
f1 = 0, f2 = 0;
f1 = fw(a, b);
f2 = fw(c, d);
long long temp, ans;
ans = 0;
long long a18 = 0, a19 = 0;
a18 = b/2018 - (a-1)/2018;
ans += a18*(d-c+1);
a19 = b/1009 - (a-1)/1009 - a18;
ans += a19*f2;
long long a28 = 0, a29 = 0;
a28 = d/2018 - (c-1)/2018;
ans += a28*(b-a+1);
a29 = d/1009 - (c-1)/1009 - a28;
ans += a29*f1;
printf("%lld\n", ans-(a19*a28+a18*(a29+a28)));
}
return 0;
}