Oiclass ASH01. 卡牌 题解

· · 题解

先放AC代码:

#include <iostream>
#include <cstdio>
using namespace std;
#define int long long

int t;

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    freopen("card.in","r",stdin);
    freopen("card.out","w",stdout);
    cin >> t;
    while (t --)
    {
        int l,r;
        cin >> l >> r;
        int ans = 0;
        if (r - l <= 3)
        {
            for(int i = l;i <= r;i ++)
                if (i % 4 != 2) ans ++;
//          cout << ans << endl;
        }
        else
            while ((r - l + 1) % 4 != 0) ans += (r % 4 != 2),r --;
        cout << ans + (r - l + 1) / 4 * 3 << endl;
    }
    return 0;
}

俗话说的好,打表过样例,暴力出奇迹。

一看样例,我们就想:只要把区间完全平方数的个数减掉就行了!

但是出题人非常的坏,特意让我们这么想。

我们只要打表一下就会发现,满足条件的规律是101110111...。

于是我们就可以把 L 和 R 移到差模 4 等于 0 的区间后,直接计算就可以了。

需要注意的是,需要特判 R-L<=3 的情况。