算法竞赛进阶指南 0x01 位运算
点击题目可以直接跳转
先来一波位运算基础知识
a^b
直接快速幂(数学相关算法可以考虑先放)
#include <iostream>
using namespace std;
typedef long long LL;//建议以后快速幂都直接LL
LL qmi(LL a, LL b, LL p)
{
LL res = 1 ;
while (b)
{
if (b & 1) res = res * a % p;
a = (LL)a * a % p;
b >>= 1;
}
return res % p;//再次取模是为了应对a^0 % p的情况(不过一般来说好像不是很需要)
}
int main()
{
LL a, b, p;
cin >> a >> b >> p;
cout << qmi(a, b, p);
return 0;
}
64位整数乘法
快速乘(和快速幂如出一辙)
#include <iostream>
using namespace std;
typedef long long LL;
LL a, b, p;
LL qml(LL a, LL b, LL p)
{
LL res = 0;
while (b)
{
if (b & 1) res = (res + a) % p;
a = a * 2 % p;
b >>= 1;
}
return res % p;//可模可不模
}
int main()
{
cin >> a >> b >> p;
cout << qml(a, b, p);
return 0;
}
最短Hamilton路径
建议等学完状压DP再回来看这题
#include <iostream>
#include <cstring>
using namespace std;
const int N = 20, M = 1 << 20;
int n, w[N][N];
int f[M][N];//f[i][j]表示从0出发当前走过的点集为i,终点为j的最短哈密顿路径
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++)
cin >> w[i][j];
memset(f, 0x3f, sizeof f);
f[1][0] = 0;//初始化 起点是0,所有状态为1,终点为0的最短哈密顿路径是0
//枚举所有state,且state必须包含起点1
for (int st = 0; st < (1<<n); st ++) if (st & 1)
for (int i = 0; i < n; i ++) if (st >> i & 1)//枚举所有当前state到过的点作为终点
//枚举以j作为终点的情况,j必须保证被经过,且不等于i
for (int j = 0; j < n; j ++) if ((st >> j & 1) && j != i)
//状态为st终点为i的情况由状态为st-(1<<i)终点为j的情况转移而来
f[st][i] = min(f[st][i], f[st - (1<<i)][j] + w[j][i]);
cout << f[(1<<n) - 1][n - 1];
return 0;
}
起床困难综合症
别看题目这么长,其实是个纸老虎
题目要求用尽可能少的体力打出最大的伤害,不仔细看的话可能会漏掉这点
题解稍微有点难以理解,用 r e s 0 res0 res0 和 r e s 1 res1 res1 分别记录当前第 b i t bit bit 位参与 n n n 次位运算后的最终结果, v a l val val 记录之前所有已经选择过的 b i t bit bit 位的状态,如果 r e s 0 < r e s 1 res0 < res1 res0<res1 并且之前的 v a l val val 加上当前第 b i t bit bit 位选择 1 1 1 之后的答案要小于等于 m m m (即 v a l + ( 1 < < b i t ) < = m val+(1<<bit)<=m val+(1<<bit)<=m ) 的话,那么明显选择 r e s 1 res1 res1 更优,如果 r e s 0 = = r e s 1 res0==res1 res0==res1 的话,因为要满足体力尽可能少的要求,所以必然是选择 0 0 0 ,其余的所有情况不外乎 v a l + ( 1 < < b i t ) > m val+(1<<bit)>m val+(1<<bit)>m 或者 r e s 0 > r e s 1 res0>res1 res0>res1 ,当然都是无脑直接选择 0 0 0 了
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
typedef pair<string, int> PSI;
int n, m;
PSI a[N];
int calc(int bit, int now)
{
for (int i = 1; i <= n; i ++)
{
int x = a[i].second >> bit & 1;
if (a[i].first == "AND") now &= x;
else if (a[i].first == "OR") now |= x;
else now ^= x;
}
return now;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++)
{
char op[5]; int x;
scanf("%s%d", op, &x);
a[i] = make_pair(op, x);
}
int val = 0, ans = 0;
for (int bit = 29; bit >= 0; bit --)//1e9不超过2^30-1,所以最多左移29位
{
int res0 = calc(bit, 0);
int res1 = calc(bit, 1);
if (val + (1<<bit) <= m && res0 < res1)
val |= 1 << bit, ans |= res1 << bit;//|写成+也行
else ans |= res0 << bit;
}
cout << ans;
return 0;
}
第一章第一节就放了难度这么大的4个题,真是对新手不友好啊!(学不懂不要紧,我当时学也没学懂,慢慢熬就完事了)