cf Educational Codeforces Round 86 C题
C. Yet Another Counting Problem
time limit per test3.5 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given two integers a and b, and q queries. The i-th query consists of two numbers li and ri, and the answer to it is the number of integers x such that li≤x≤ri, and ((xmoda)modb)≠((xmodb)moda). Calculate the answer for each query.
Recall that ymodz is the remainder of the division of y by z. For example, 5mod3=2, 7mod8=7, 9mod4=1, 9mod9=0.
Input
The first line contains one integer t (1≤t≤100) — the number of test cases. Then the test cases follow.
The first line of each test case contains three integers a, b and q (1≤a,b≤200; 1≤q≤500).
Then q lines follow, each containing two integers li and ri (1≤li≤ri≤1018) for the corresponding query.
Output
For each test case, print q integers — the answers to the queries of this test case in the order they appear.
Example
input
2
4 6 5
1 1
1 3
1 5
1 7
1 9
7 10 2
7 8
100 200
output
0 0 0 2 4
0 91
题目大意:对于每个查询,打印出满足x∈[li, ri],且((xmod a) mod b) ≠ ((x mod b)mod a) 的个数。
思路:这道题刚拿到手我也不知道怎么做,但有一点很明显,如果暴力肯定超时,然后我根据题目意思,进行了小规模的模拟,看出了这道题的解法。
上图:
不知道你们有没有看出来,符和i%a%b == i% b%a 的i∈[n×lcm(a, b), n×lcm(a, b) + max(a, b) - 1],如果这个看出来,这道题思路就有了,接下来最难的部分就是处理边界。
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
ll arr[600] = {0};
ll a, b, q;
scanf("%lld%lld%lld", &a, &b, &q);
ll lcm = a * b / gcd(a, b);
for(int j = 1; j <= q; j++)
{
ll rem ;
ll rem2, li, ri;
ll result = 0;
scanf("%lld%lld", &li, &ri);
rem = li / lcm;
rem2 = ri / lcm;
for(ll i = rem * lcm; i < li; i++)/*减去左边边界前面的部分*/
{
if((ll)(i - rem * lcm) < max(a, b))
result--;
else
break;
}
result += (rem2 - rem) * max(a, b);
for(ll i = rem2 * lcm + 1; i <= ri; i++)/*加上右边边界前面的部分*/
{
if((ll)(i - rem2 * lcm) < max(a, b))
result++;
else
break;
}
result = (ri - li) - result;/*取反*/
arr[j] = max((ll)(0), result);
}
for(int j = 1; j <= q; j++)
printf("%lld ", arr[j]);
printf("\n");
}
return 0;
}
推荐阅读
-
Educational Codeforces Round 60 (Rated for Div. 2) ----A - Best Subsegment(思维题)
-
Codeforces Round #656 (Div. 3) (C、D题)
-
Educational Codeforces Round 85 (Rated for Div. 2) C. Circle of Monsters(前缀和 预处理 贪心)
-
Codeforces Round #657 (Div. 2) C题
-
Codeforces Round #277.5 (Div. 2)(C题)_html/css_WEB-ITnose
-
Educational Codeforces Round 99 (Rated for Div. 2) C. Ping-pong
-
C. Mortal Kombat Tower(动态规划)Educational Codeforces Round 95 (Rated for Div. 2)
-
Educational Codeforces Round 88 (Rated for Div. 2)C. Mixing Water[题解](数学)
-
Educational Codeforces Round 31-k叉哈夫曼&优先队列&好题-D. Boxes And Balls
-
Educational Codeforces Round 95 (Rated for Div. 2)C. Mortal Kombat Tower【dp】