这么暴力的dfs
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10,M = 2e6 + 10;
int n;
int h[N],e[M],ne[M],idx;
int d[N],color[N];
LL tot;
void add(int a,int b){
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
void dfs(int u,int father,int depth){
d[u] = depth;
for(int i=h[u];~i;i=ne[i]){
int j = e[i];
if(j == father) continue;
dfs(j,u,depth+1);
}
}
void dfs_draw(int u,LL s0,LL s1){
if(s0 > tot / 2 || s1 > tot / 2) return ;
if(u > n){
if(s0 == s1){
for(int i=1;i<=n;i++) printf("%d ",color[i]);
exit(0);
}
return ;
}
color[u] = 0;
dfs_draw(u + 1,s0 + d[u],s1);
color[u] = 1;
dfs_draw(u + 1,s0,s1 + d[u]);
}
int main(){
memset(h,-1,sizeof(h));
scanf("%d",&n);
for(int i=1;i<n;i++){
int a,b;
scanf("%d %d",&a,&b);
add(a,b);
add(b,a);
}
dfs(1,-1,1);
for(int i=1;i<=n;i++) tot += d[i];
if(tot & 1){
puts("-1");
return 0;
}
dfs_draw(1,0,0);
puts("-1");
return 0;
}
最开始没加
if(tot & 1){
puts("-1");
return 0;
}
是5分,除了第一个subtask,其他的都有TLE,加了这个全过了