这是一道需要优化的暴力的题。
一、暴力x分(我也不知道多少分)(思路简单,得分凉凉)。
- 建立
now求异或和。 - 枚举每一位。
- 枚举每一个数。
- 判断是否用过。
- 判断异或和是否为 。
- 加上这一位。
- 如果这一位为空则输出
impossible。 - 统计答案。
cude :
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<unordered_map>
#include<cstring>
#include<algorithm>
#include<cmath>
//using namespace std;
#define int long long
#define oc(c) putchar(c);
#define nl oc('\n');
const int N = 1e5 + 5;
int n,p[N],now,T;
bool vis[N];
void in(int &n) {
char ch = getchar();
int f = 1,ans = 0;
while(ch < '0' || ch > '9') {
if(ch == '-') f *= -1;
ch = getchar();
}
while(ch <= '9' && ch >= '0') ans = (ans << 1) + (ans << 3) + ch - '0',ch = getchar();
n = ans * f;
}
void out(int n) {
if(n < 0) putchar('-'),n *= -1;
if(n > 9) out(n / 10);
putchar(n % 10 + '0');
}
void out(int n,char c) {
out(n),putchar(c);
}
void solve() {
memset(vis,0,sizeof vis);//多测不清空......
memset(p,-1,sizeof p);//序列里面有0千万别设0,调了许久
in(n);
now = 0;//记得清空now
for(int i = 1;i <= n;i ++){
for(int j = 0;j < n;j ++){
if(vis[j]) continue;//是否被用过
if((now ^ j) == 0) continue;//异或和是否为0
p[i] = j;//记录
vis[j] = 1;//标记
now ^= j;//别忘了改变now
break;//跳出!不然会记录多次
}
if(p[i] == -1) {
puts("impossible");
return;
}
}
for(int i = 1;i <= n;i ++){
out(p[i],' ');
}
nl;
}
signed main() {
// freopen("p.out","w",stdout);
// freopen("p.in","r",stdin);
in(T);
while(T --) {
solve();
}
return 0;
}二、链表优化。
虽说 for 循环里有 continue 有 break 。
但 必定每个都用,复杂度 都来一次,总体来说复杂度为 。
所以这里可以优化掉一个 continue ——建一个含有 的链表,把用过的数从链表里丢出去,每次枚举链表里的数,以此判断与 now 异或是否为 。
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<unordered_map>
#include<cstring>
#include<algorithm>
//using namespace std;
//#define int long long
#define oc(c) putchar(c)
#define nl oc('\n')
const int N = 1e6 + 5;
int n,nxt[N],pre[N],head,end,T,a[N],now,p[N];
void in(int &n) {
char ch = getchar();
int f = 1,ans = 0;
while(ch < '0' || ch > '9') {
if(ch == '-') f *= -1;
ch = getchar();
}
while(ch <= '9' && ch >= '0') ans = (ans << 1) + (ans << 3) + ch - '0',ch = getchar();
n = ans * f;
}
void out(int n) {
if(n < 0) putchar('-'),n *= -1;
if(n > 9) out(n / 10);
putchar(n % 10 + '0');
}
void out(int n,char c) {
out(n),putchar(c);
}
void solve() {
in(n);
memset(p,-1,sizeof p);
head = 0,end = n + 1,now = 0;//head,end设为边界外方便处理
nxt[head] = 1,pre[end] = n;//边界别忘初始化
for(int i = 1; i <= n; i ++) {//链表初始化
pre[i] = i - 1;//i的上一个编号为i-1
nxt[i] = i + 1;//i的下一个编号为i+1
a[i] = i - 1;//值为i-1,千万不是i
}
for(int i = 1; i <= n; i ++) {
for(int it = nxt[head]; it != end; it = nxt[it]) {//枚举链表元素
//链表元素默认没用过且升序,符合异或和标准即可
if((now ^ a[it]) != 0) {
pre[nxt[it]] = pre[it];
nxt[pre[it]] = nxt[it];//删除it
now ^= a[it];//改值
p[i] = a[it];//记录
break;
}
}
if(p[i] == -1) {
puts("impossible");
return;
}
}
for(int i = 1; i <= n; i ++) {
out(p[i],' ');
}
nl;
}
signed main() {
// freopen("p.out","w",stdout);
// freopen("p.in","r",stdin);
in(T);
while(T --) {
solve();
}
return 0;
}