题目总结
今日的位运算专题,做的不太理想满分500分,只打了96分,可能是考试时状态不太好导致的。其实前三题都比较水。接下来总结一下每道题的思路及代码。
题单:
P7071 [CSP-J 2020] 优秀的拆分
P1461 [USACO2.1] 海明码 Hamming Codes
P13591 [NWRRC 2023] Kitchen Timer
P11485 「Cfz Round 5」Non-breath Oblige
P10307 「Cfz Round 2」Binary总结:
P7071 [CSP-J 2020] 优秀的拆分
错因:
★★★的返回值是类型的,碰到大数据会自动变成科学计数法,应该先转类型再输出,或者写左移。
思路:
. 从到倒序遍历判断是否小于,如果小于,那么证明二进制中的第位为,就用减去,再输出即可。
. 从的第位遍历到第位,看它是否为,如果为,即二进制中的第位为,输出即可。
代码:
#include <bits/stdc++.h>
using namespace std;
int n;
int main(){
cin >> n;
if(n % 2){
cout << -1;
return 0;
}
for(int i = 30; i >= 1; i--)
if((1 << i) <= n)
n -= (1 << i), cout << (1 << i) << ' ';
return 0;
} 或
#include <bits/stdc++.h>
using namespace std;
int n;
int main(){
cin >> n;
if(n % 2){
cout << -1;
return 0;
}
for(int i = 30; i >= 1; i--)
if(n >> i & 1) cout << (1 << i) << ' ';
return 0;
}或
#include <bits/stdc++.h>
using namespace std;
int n;
int main(){
cin >> n;
if(n % 2){
cout << -1;
return 0;
}
for(int i = 30; i >= 1; i--)
if(n >> i & 1) cout << int(pow(2, i)) << ' ';
return 0;
}P1461 [USACO2.1] 海明码 Hamming Codes
错因:
不知道如何求 距离及如何存储这个编码。
思路:
先要明确一定为第一个编码,再无限循环遍历,检查是否符合要求。这其中创建一个数组,用来存储个编码,还有一个数量,用来换行及。
那么如何检查是否符合要求呢?用 距离。两个编码的 距离即为每一位两编码相同的数量。只要用与每一个数组中的编码判断,如果合法,就存起来并输出。
这里有一个问题:每输出个编码换一行,那么这里就必须要用一个变量存储数量,不然不知道什么时候有个编码,而且还要确定停止时间
代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, b, d, cnt = 1, idx[70];
int hm(int x, int y){
int cc1 = 0;
for(int i = 60; i >= 0; i--){
int p = x >> i & 1;
int q = y >> i & 1;
cc1 += (p != q);
}
return cc1;
}
signed main(){
cin >> n >> b >> d;
cout << 0 << ' ';
for(int i = 1; ; i++){
bool flag = true;
for(int j = 1; j <= cnt; j++)
if(hm(idx[j], i) < d) flag = false;
if(flag){
idx[++cnt] = i;
cout << idx[cnt] << ' ';
if(cnt % 10 == 0) cout << '\n';
if(cnt == n) return 0;
}
}
return 0;
} P13591 [NWRRC 2023] Kitchen Timer
错因:
没有抓住做题的关键。
思路:
如果要让按暂停键的次数最少,那么就要让连续按按钮的次数最多。如果连续按了次,那么总次数就为。明确了这一点,我们将从可能中的最大值(1ll << 63) - 1开始遍历,若,即中包含,那么就将这一部分剪掉,然后按一次暂停键,最后的答案因为要避开第一组,所以得减去。然后每按一次暂停键,就得除以
代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
int t, x;
void solve(){
cin >> x;
int k = (1ll << 63) - 1, ans = 0;
while(x != 0){
while(x >= k){
x -= k;
ans++;
}
k /= 2;
}
cout << ans - 1 << '\n';
}
signed main(){
cin >> t;
while(t--)
solve();
return 0;
}P11485 「Cfz Round 5」Non-breath Oblige
错因:
没想到思路。
思路:
首先,如果一开始就等于,那么输出即可。
然后排除特殊情况,也就是,那么答案为
(s ^ ((1 << n) - 1)) + (t ^ ((1 << n) - 1))证明: 如果,要使,的代价之和最小,那么将变成,再将变成所需的代价之和一定会其它所花费的代价。这时 = ,一定保证满足条件,证毕!
代码:
#include <bits/stdc++.h>
using namespace std;
int T, n, s, t;
void solve(){
cin >> n >> s >> t;
if(s == t) cout << "0\n";
else cout << (s ^ ((1 << n) - 1)) + (t ^ ((1 << n) - 1)) << '\n';
}
int main(){
cin >> T;
while(T--)
solve();
return 0;
}