A - Alchemy 101
题意: 输入一个数m,求出从1到m中异或和等于m且是所有情况中包含的数字最多和字典序最小的那一串数。
我的想法相当暴力,就是先求出从1到m的异或和,如果等于m那就直接输出,否则就bfs从m到1与每个数进行异或运算,如果等于m就输出,否则就将其异或结果放进队列中,一直到那一串数。
当然还有其他更简单的方法,先放上代码。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define ll long long
using namespace std;
const int N = 1e4+10;
int n,m,t;
int ans,vis[N];
int cnt,flag;
struct node {
int sum,num;
int book[N];
}s;
void bfs(int ans) {
queue<node>q;
s.sum = ans;
s.num = m;
for(int i=1; i<=m; i++) {
s.book[i] = 0;
}
q.push(s);
while(!q.empty()) {
node now = q.front();
q.pop();
for(int i=m; i>=1; i--) {
int temp = now.sum^i;
if(temp==m&&!now.book[i]) {
now.book[i] = 1;
now.num--;
cout<<now.num<<endl;
int ok=0;
for(int i=1; i<=m; i++) {
if(!now.book[i]) {
if(!ok) {
ok=1;
cout<<i;
}
else cout<<' '<<i;
}
}
cout<<endl;
flag=1;
break;
}
}
if(flag) break;
else {
for(int i=m; i>=1; i--) {
if(!now.book[i]) {
now.sum = now.sum^i;
now.book[i] = 1;
now.num = now.num-1;
q.push(now);
}
}
}
}
}
int main() {
scanf("%d",&t);
while(t--) {
ans=0;
flag=0;
scanf("%d",&m);
for(int i=1; i<=m; i++) ans^=i;
if(ans==m) {
int ok=0;
cout<<m<<endl;
for(int i=1; i<=m; i++) {
if(!ok) {
ok=1;
cout<<i;
}
else cout<<' '<<i;
}
cout<<endl;
}
else bfs(ans);
}
return 0;
}
来自某位大佬的更简洁的代码:
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
int a[10005];
void solve(int n) {
int k = 0, j = 0, x, len, y;
x = n ^ a[n];
int ans = 0, t = 1;
while (x) {
if (x & 1) ans += t;
t *= 2;
x >>= 1;
}
x = -1;
if (ans == 0)
len = n;
else {
len = n - 1;
x = ans;
}
cout << len << "\n";
int flag = 1;
for (int i = 1; i <= n; i++) {
if (i == x)
continue;
else if (flag == 1) {
cout << i;
flag = 0;
} else
cout << ' ' << i;
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
int t, n;
a[1] = 1;
for (int i = 2; i <= 1005; i++) {
a[i] = a[i - 1] ^ i;
}
cin >> t;
while (t--) {
cin >> n;
solve(n);
}
}