超级超级超级“水”的题

· · 题解

题目传送门

分析题目

给定两个正整数 n ,m ,求出一个非负整数 n 操作 k 次以下操作的值 :n ← n & max ( n − m , 0 )。

第一眼看上去真的简单炸了,但数据却对你开了一个玩笑。

这是我第一眼想出来的代码 :

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t;
    cin >> t;
    for(int r = 1;r <= t;r++)
    {
        int n,m,k;
        cin >> n >> m >> k;
        if(n <= m) cout << 0 << endl;
        else
        {
            int ans = n;
            for(int i = 1;i <= k;i++) ans = ans & max(ans-m,0);
            cout << ans << endl;
        }

    }
    return 0;
}

思路很对,但有两个点 TLE 。

优化策略

首先想到的一定是尽量减少循环次数吧。那么根据题意,在每一轮加上一组判断,如果这里的差小于零,那么就把答案更新为零,然后跳出循环。剩下的按正常做,这样就会节省很多时间。

上 AC 代码

#include <bits/stdc++.h>
using namespace std;

int main() 
{
    int t;
    cin >> t;
    for(int qwq = 1;qwq <= t;qwq++) 
    {
        long long n, m, k;
        cin >> n >> m >> k;
        long long ans = n;
        for (int i = 1;i <= k;i++) 
        {
            if(ans < m) 
            {
                ans = 0;
                break;
            }
            long long c = ans & (ans - m);
            if(c == ans) break;
            ans = c;
        }
        cout << ans << endl;
    }
    return 0;
}

感谢大佬们观看,蟹蟹啦。