1024 Magic Island

TAG 搜索  dfs bfs

深度优先、宽度优先都行。

因为没有用STL 用静态数组分配节点,速度很不错  0.22 sec 808 KB

/* source code of submission 427641, Zhongshan University Online Judge System */ #include <stdio.h> #include <memory.h> const int N=10000; struct tnode { int v,dist,next; }; int dist[N]; int g[N]; bool visited[N]; int n,k,ans; int a,b,c; tnode node[N*2]; int nlen; void search(int root, int d ) { bool isleaf=true; int p=g[root]; while ( p!=-1) { if ( !visited[ node[p].v ] ) { isleaf=false; visited[ node[p].v ]=true; search(node[p].v, d+node[p].dist ); } p=node[p].next; } if ( isleaf ) { ans= ans<d? d: ans; } } int main(int argc, char *argv[]) { while ( scanf("%d%d", &n, &k)!=EOF ) { nlen=-1; memset(g, -1, sizeof(g) ); for (int i=0; i<n-1; ++i) { scanf("%d%d%d", &a, &b, &c); if ( a>b ) { int tmp=a; a=b; b=tmp; } --a; --b; ++nlen; node[nlen].dist=c; node[nlen].v=b; node[nlen].next=g[a]; g[a]=nlen; ++nlen; node[nlen].dist=c; node[nlen].v=a; node[nlen].next=g[b]; g[b]=nlen; } ans=0; memset(visited, false, sizeof(visited) ); visited[k-1]=true; search(k-1,0); printf("%d/n",ans ); } return 0; }

你可能感兴趣的:(c,struct,search,System)