题解:P16337 「ALFR Round 10」Bit Problem

· · 题解

请先看题

题目意思 :

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

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

也可以转成这个样子 :

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

题目思路和优化 :

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

暴力代码 :

#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 :

设这个数是 5 :

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

结果是 0

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

#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-m 一定比 n 小 , 所以 n\%max(n-m,0) 也就一定比 n 小 , 因此可以得出 , 用不了几次 , n-m 也就小于 0 了 , 这时候我们再去判 , 就可以了 。

AC 代码 :

#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;
}

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