题解:P13336 [GCJ 2012 Finals] Shifting Paths
确实是道折半搜索神题。
神在:
- 如何分成两半。
- 证明在
B 部分暴力走为何能保证时间复杂度。如何分半
对于它给的图,从点
n 在反图进行 bfs,算出每个点u 的以n 为根的 bfs 生成树中的dep_u 。
然后将
这样就分成两半了。
对 A 部分进行预处理
令
- 0:所在的点
nu 的编号。 - 1:
A 集合所有点的经过次数的奇偶性状态。 - 2:路径长度。
这个可以
对 B 部分暴力走
有了
这样就做完了,但时间复杂度方面上,对于
结论:在到达点
:::info[证明]
设路径序列
假设存在
那么
又因
不断向
| 这与我们假设“在到达 |
|---|
根据上面的代码复杂度分析总时间复杂度为
//#pragma GCC optimize(1,2,3,"Ofast","inline")
#include<bits/stdc++.h>
#define fi first
#define se second
#define pi pair<int,int>
#define cint const int &
typedef long long ll;
using namespace std;
const int N=44;
int T;
int n;
int son[N][2];
int ta[N],tb[N],rta[N],rtb[N];
int vis[N][(1<<21)];
vector<int> e[N];
int dep[N];
vector<int> V;
struct node{
int v,S; ll len;
};
node dp[N][(1<<21)];
void clear(){
V.clear();
for(int i=1;i<=n;i++){
e[i].clear();
dep[i]=0;
ta[i]=rta[i]=0;
tb[i]=rtb[i]=0;
}
}
void bfs(){
queue<int> q;
q.push(n);
dep[n]=1;
while(q.size()){
int u=q.front();
q.pop();
V.push_back(u);
for(int v:e[u])
if(!dep[v]){
dep[v]=dep[u]+1;
q.push(v);
}
}
}
bool dfs(cint u,cint S){
if(vis[u][S]==2) return true;
if(vis[u][S]==1) return false;
vis[u][S]=1;
int nS=S^(1<<(u-1));
int ru=rta[u];
int v=son[ru][nS>>(u-1)&1];
if(tb[v]||v==n){
dp[u][S]={v,nS,1};
vis[u][S]=2;
return true;
}
if(!ta[v]){
return false;
}
v=ta[v];
bool tf=dfs(v,nS);
if(tf){
dp[u][S]=dp[v][nS];
dp[u][S].len++;
}
vis[u][S]+=tf;
return tf;
}
ll get_ans(int u){
int Sa=0,Sb=0;
ll res=0;
while(u!=n){
if(ta[u]){
if(vis[ta[u]][Sa]==1) return -1;
auto &tmp=dp[ta[u]][Sa];
u=tmp.v;
Sa=tmp.S;
res+=tmp.len;
}else if(tb[u]){
Sb^=(1<<(tb[u]-1));
u=son[u][Sb>>(tb[u]-1)&1];
res++;
}else return -1;
}
return res;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>T;
int t=0;
while(++t<=T){
cin>>n;
clear();
for(int i=1;i<n;i++){
cin>>son[i][1]>>son[i][0];
e[son[i][0]].push_back(i);
e[son[i][1]].push_back(i);
}
bfs();
// cerr<<"Case #"<<t<<"\n";
cout<<"Case #"<<t<<": ";
if(!dep[1]){
cout<<"Infinity\n";
continue;
}
int Bs=V.size()/2+2;
vector<int> A,B;
for(int i=0;i<Bs;i++){
B.push_back(V[i]);
tb[V[i]]=B.size();
rtb[B.size()]=V[i];
}
for(int i=Bs;i<V.size();i++){
A.push_back(V[i]);
ta[V[i]]=A.size();
rta[A.size()]=V[i];
}
for(int i=1;i<=A.size();i++)
for(int j=0;j<(1<<A.size());j++)
vis[i][j]=0;
for(int i=1;i<=A.size();i++)
for(int j=0;j<(1<<A.size());j++)
dfs(i,j);
ll ans=get_ans(1);
if(ans==-1) cout<<"Infinity\n";
else cout<<ans<<"\n";
}
return 0;
}
:::