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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值