title: 261123周一晚 - 位运算 author: wu_sir date: 2026-11-23 organization: 河源高级中学 header: title————{title} ———— {author}(organization)footer:起始于:{organization}) footer: 起始于:{date} - - - - - - 第 pageNo页/共{pageNo} 页 / 共 {pageCount} 页 - - - - - - 终止于:${today} keywords:

  • 二进制

位运算

#C1236. 系列按位运算最大值 [NOI2014]

code
	int n, m;	cin >> n >> m;
	int x0 = 0, x1 = -1;
	for(int i = 1; i <= n; i ++) {
		string s;	cin >> s;
		int w;	cin >> w;
		if(s == "AND") x0 &= w, x1 &= w;
		else if(s == "OR") x0 |= w, x1 |= w;
		else x0 ^= w, x1 ^= w;
	}
	while(m --) {
		int w;	cin >> w;
		int x = 0, ans = 0;
		for(int k = 29; k >= 0; k --) {
			if(x0 >> k & 1) x += 0, ans += 1 << k;
			else if((x1 >> k & 1) && x + (1 << k) <= w) x += 1 << k, ans += 1 << k;
			else x += 0, ans += 0;
		}
		cout << ans << ' ';
	}
	cout << endl;

#C1237. 调整使得区间异或能为 k

code
const int N = 5e5 + 9, inf = 1e9 + 9;
int a[N], b[N];

void solved() {
	int n, m;	cin >> n >> m;
	for(int i = 1; i <= n; i ++) cin >> a[i];
	sort(a + 1, a + n + 1);
	while(m --) {
		int w;	cin >> w;
		int cnt = min(n, 30), ans = 0;
		for(int i = 1; i <= cnt; i ++) b[i] = a[n - i + 1];
		for(int k = 29; k >= 0; k --) {	// 从高位开始枚举
			if(~w >> k & 1) continue;	// 这一位无需拼出
			int pos = 1;	// 找到最大值所在位置
			for(int i = 2; i <= cnt; i ++) if(b[i] > b[pos]) pos = i;
			if((1 << k) <= b[pos]) ans += 0, b[pos] -= 1 << k;
			else ans += (1 << k) - b[pos], b[pos] = 0;
		}
		cout << ans << ' ';
	}
	cout << endl;
}

0 条评论

目前还没有评论...