求樹的直徑-模板
阿新 • • 發佈:2019-02-13
sizeof bit put digi als code struct lse utc
#include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f #define MAXN 1000010 #define MAXM 5010 inline int read() { int x = 0,ff = 1;char ch = getchar(); while(!isdigit(ch)) { if(ch == ‘-‘) ff = -1; ch = getchar(); } while(isdigit(ch)) { x= (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * ff; } inline void write(int x) { if(x < 0) putchar(‘-‘),x = -x; if(x > 9) write(x / 10); putchar(x % 10 + ‘0‘); } int a,b,dis[MAXN],vis[MAXN],ans,point; int lin[MAXN],tot = 0; struct edge {int y,v,next; }e[MAXN]; inline void add(int xx,int yy,int vv) { e[++tot].y = yy; e[tot].v = vv; e[tot].next = lin[xx]; lin[xx] = tot; } void BFS(int s) { ans = 0; memset(dis,0,sizeof(dis)); memset(vis,false,sizeof(vis)); queue < int > q; q.push(s); vis[s] = true; point = s; while(!q.empty()) { int x = q.front(); q.pop(); for(int i = lin[x],y;i;i = e[i].next) { if(!vis[y = e[i].y]) { q.push(y); vis[y] = true; dis[y] = dis[x] + e[i].v; if(dis[y] > ans) ans = dis[y],point = y; } } } } int main() { a = read(); for(int i = 1;i <= a;++i) { int x,y,v; x = read(); y = read(); v = read(); add(x,y,v); add(y,x,v); } BFS(1); BFS(point); write(ans); return 0; }
求樹的直徑-模板