跳到正文

题解

题解:P16337 「ALFR Round 10」Bit Problem

LZYGcaixukun约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年4月19日
收录
2026年5月10日
更新
2026年11月17日
篇幅
约 3 分钟
题目
P16337

版本

  1. v1当前

请先看题

题目意思 :

意思很明白 , 就是让我们操作 kk 次以下公式 :

n←n &max⁡(n−m,0)n\leftarrow n\text{ \&}\max(n-m,0)

也可以转成这个样子 :

C++
n=n&max(n-m,0);  貌似没什么区别

题目思路和优化 :

因为数据很大 ,所以不能暴力 ,暴力只得 50 分 :

暴力代码 :

C++
#include <bits/stdc++.h>
using namespace std;
long long t;
int main(){
    cin>>t;
    while(t--){
        int n,m,k;
        cin>>n>>m>>k;
        while(k--)n=n&max(n-m,0);
        cout <<n<<'\n';
    }
    return 0;
}

那我们就要去优化 , 我们不难发现一个规律 , 一个数 &\& 0 永远是 0 :

C++
设这个数是 5 :

      1  0  1
      0  0  0
    -----------
      0  0  0

结果是 0

所以我们把这个特判加进去 :

C++
#include <bits/stdc++.h>
using namespace std;
long long t;
int main(){
    cin>>t;
    while(t--){
        int n,m,k;
        cin>>n>>m>>k;
        if(n-m<=0){//特判
            cout <<"0\n";
            continue;
        }
        while(k--)n=n&max(n-m,0);
        cout <<n<<'\n';
    }
    return 0;
}

可是还是不行 , 因为一旦进了循环 , 特判就毫无用处了 。

可否再优化呢 , 答案是可以的 , 我们不难发现 , n%max(n−m,0)n\%max(n-m,0) 里的 n−mn-m 一定比 nn 小 , 所以 n%max(n−m,0)n\%max(n-m,0) 也就一定比 nn 小 , 因此可以得出 , 用不了几次 , n−mn-m 也就小于 0 了 , 这时候我们再去判 , 就可以了 。

AC 代码 :

C++
#include <bits/stdc++.h>
using namespace std;
long long t;
int main(){
    cin>>t;
    while(t--){
        int n,m,k,v=1;
        cin>>n>>m>>k;
        if(n-m<=0){//特判一
            cout <<"0\n";
            continue;
        }
        while(k--){
            if(n-m<=0){//再次特判
                cout <<"0\n";
                v=0;break;
            }
            n=n&max(n-m,0);
        }
        if(v==1)cout <<n<<'\n';//最后避免重复输出
    }
    return 0;
}

结语 , 求管理员大大通过 。

原文