欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cf Educational Codeforces Round 86 C题

程序员文章站 2022-06-04 18:21:19
...

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) 的个数。
思路:这道题刚拿到手我也不知道怎么做,但有一点很明显,如果暴力肯定超时,然后我根据题目意思,进行了小规模的模拟,看出了这道题的解法。
上图:

cf Educational Codeforces Round 86 C题

cf Educational Codeforces Round 86 C题
cf Educational Codeforces Round 86 C题

不知道你们有没有看出来,符和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;
}