代码1:最慢的点 >1200ms TLE
#include<bits/stdc++.h>
using namespace std;
#define isdigit(x) (x>='0'&&x<='9')
char *p1,*p2,*pp,buf[1<<20],pbuf[1<<20];
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
#define endl putchar('\n')
#define space putchar(' ')
int qr(){
int f=1,x=0;char ch=gc();
while(!isdigit(ch))f=(ch==45)?-1:1,ch=gc();
while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=gc();
return x*f;
}
void qw(int x){
if(x<0)putchar(45),x=-x;
if(x>9)qw(x/10);
putchar(x%10+48);
}
int n,k,cnt;
int used[1<<20],v[1<<20];
void dfs(int x,int dep){
if(dep>(1<<n))exit(0);
qw(x);
space;
used[x]=1;
for(int i=1;i<=cnt;i++)
if(!used[v[i]^x])
dfs(v[i]^x,dep+1);
}
int main(){
n=qr(),k=qr();
for(int i=0;i<(1<<n);i++)
if(__builtin_popcount(i)==k)
v[++cnt]=i;
dfs(0,1);
return 0;
}
代码2:最慢的点 131ms AC
#include<bits/stdc++.h>
using namespace std;
#define isdigit(x) (x>='0'&&x<='9')
char *p1,*p2,*pp,buf[1<<20],pbuf[1<<20];
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
#define endl putchar('\n')
#define space putchar(' ')
int qr(){
int f=1,x=0;char ch=gc();
while(!isdigit(ch))f=(ch==45)?-1:1,ch=gc();
while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=gc();
return x*f;
}
void qw(int x){
if(x<0)putchar(45),x=-x;
if(x>9)qw(x/10);
putchar(x%10+48);
}
int n,k,cnt;
int used[1<<20],v[1<<20];
vector<int>ans;
void dfs(int x,int dep=1){
qw(x);
space;
ans.push_back(x);
if(ans.size()==(1<<n)){
exit(0);
}
used[x]=1;
for(int i=1;i<=cnt;i++)
if(!used[v[i]^x])
dfs(v[i]^x,dep+1);
}
int main(){
n=qr(),k=qr();
for(int i=0;i<(1<<n);i++)
if(__builtin_popcount(i)==k)
v[++cnt]=i;
dfs(0);
return 0;
}
两份代码只有在 dfs 函数上有区别。
评测环境:C++14 (GCC 9) O2