Speaking are tears ah
T3's bfs been wrong, I want to die.
Gou two hours examination time, life and death can not find the error (because lca and discrete codes are out, too messy)
Finally bfs singled, found inside bfs output f [ly] [0] are correct, completely collapse out to the outside, are all 0.
And he transferred a lesson, and finally found
Array bounds up. . .
error code
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #define rint register int using namespace std; int n,m,a,b,tot,first[100005]; int deep[100005],f[100005][18]; struct node{ int u,v,nxt; }edge[100005]; inline void add(int u,int v) { ++tot; edge[tot].u=u; edge[tot].v=v; edge[tot].nxt=first[u]; first[u]=tot; } inline void bfss() { queue <int> q; deep[1]=1; q.push(1); while(!q.empty()) { int lq=q.front();q.pop(); for(rint i=first[lq];i;i=edge[i].nxt) { int ly=edge[i].v; if(ly==0)continue; if(deep[ly])continue; deep[ly]=deep[lq]+1; f[ly][0]=lq; cout<<ly<<":fa:"<<f[ly][0]<<endl; // cout<<f[20][0]<<endl; for(rint j=1;j<=18;++j) { f[ly][j]=f[f[ly][j-1]][j-1]; printf("f[%d][%d]=%d\n",ly,j,f[ly][j]); } q.push(ly); } } return ; } int main() { scanf("%d %d",&n,&m); for(rint i=1;i<n;++i) { scanf("%d %d",&a,&b); add(a,b);add(b,a); } bfss(); cout<<f[20][0]<<endl; }
Correct codes
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #define rint register int using namespace std; int n,m,a,b,tot,first[100005]; int deep[100005],f[100005][18]; struct node{ int u,v,nxt; }edge[100005]; inline void add(int u,int v) { ++tot; edge[tot].u=u; edge[tot].v=v; edge[tot].nxt=first[u]; first[u]=tot; } inline void bfss() { queue <int> q; deep[1]=1; q.push(1); while(!q.empty()) { int lq=q.front();q.pop(); for(rint i=first[lq];i;i=edge[i].nxt) { int ly=edge[i].v; if(ly==0)continue; if(deep[ly])continue; deep[ly]=deep[lq]+1; f[ly][0]=lq; cout<<ly<<":fa:"<<f[ly][0]<<endl; // cout<<f[20][0]<<endl; for(rint j=1;j<=17;++j) { f[ly][j]=f[f[ly][j-1]][j-1]; printf("f[%d][%d]=%d\n",ly,j,f[ly][j]); } q.push(ly); } } return ; } int main() { scanf("%d %d",&n,&m); for(rint i=1;i<n;++i) { scanf("%d %d",&a,&b); add(a,b);add(b,a); } bfss(); cout<<f[20][0]<<endl; }
How do I want to die. . .