XOR运算
近來做了一些題目和異或運算有關的題目,總結一下
Xor
按位異或
符號在編程語言中通常是 ^或xor
數學符號通常用⊕表示
X = 0101B
Y = 1011B
| 1 | 0 | 1 |
| 1 | 1 | 0 |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
X^Y = 1110B
性質
1. 0 ^ 0 = 0
2.a ^ a = 0
3.0 ^ 1 ^ 2 … ^ n的性質
先觀察一下如下的 序列
我們暴力計算出前50項的異或和,觀察規律
不難得出每隔四項的異或和都為0
并且每四項都是以1 N-1 0 N這四項為規律
這里N取第一個大于等于n且是4的倍數的數
所以我們想要求得第1項到第n項的異或和的結果
只需要異或
4.[l,r]區間的異或和
l ^ l + 1 ^ l + 2^… ^ r = (1 ^ 2… ^ l ) ^ (1 ^ 2 ^ 3… ^ r)
所以如果我們要求一個區間段的異或和,只需要求(1-l) 的異或和 ^ (1-r)的異或和
證明 1 ^ 2 ^ 3 ... ^ l 1 ^ 2 ^ 3... ^l ^ l+1 ^l+2 ....^ r-1 ^ r 很容易發現1^2^3...l相同,則異或和為0傳送門
XOR Sum
Xor Sums
#include <bits/stdc++.h> using namespace std; typedef long long ll; int t;void solved() {ll ans = 0,n;cin >> n;while (n % 4 != 3 && n >= 0) {ans ^= n; n --;} }int main() {cin >> t;while (t --) solved();return 0; }Blocks
#include <bits/stdc++.h>#define ll long long #define all(aaa) aaa.begin(), aaa.end()using namespace std;signed main() {ios_base::sync_with_stdio(0);cin.tie(NULL);string t;int n;cin >> n >> t;for (char c : {'W', 'B'}) {string s = t;vector<int> v;for (int i = 0; i < n - 1; i++) {if (s[i] != c) {v.push_back(i);s[i] = (s[i] == 'W' ? 'B' : 'W');s[i + 1] = (s[i + 1] == 'W' ? 'B' : 'W');}}if (s[n - 1] == c) {cout << v.size() << "\n";for (int x : v)cout << x + 1 << " ";cout << "\n";return 0;}}cout << -1;return 0; }Dr. Evil Underscores
#include <bits/stdc++.h> #define N 100010 #define CINSPEED std::ios::sync_with_stdio(false),std::cin.tie(0),std::cout.tie(0) using namespace std; typedef long long ll;int n;int dfs(vector<int> t,int i) {vector<int>one,zero;if(i < 0 || t.size() == 0)return 0;for(auto & j : t){if(j >> i & 1)one.push_back(j);else zero.push_back(j);}if(!zero.size())return dfs(one,i - 1);if(!one.size())return dfs(zero,i - 1);return min(dfs(one,i - 1),dfs(zero,i - 1))|(1 << i); }int main() {cin >> n;vector<int> k(n);for(int i = 0;i < n;i++)cin >> k[i];cout << dfs(k,30); #ifdef LOCALsystem("pause"); #endifreturn 0; }總結
- 上一篇: xor运算java_java - 使用
- 下一篇: Grid Xor