标签:
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <cctype> #include <vector> #include <iterator> #include <set> #include <map> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define spf sprintf #define pb push_back #define debug printf("!\n") #define MAXN 40000+5 #define MAX(a,b) a>b?a:b #define blank pf("\n") #define LL long long #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) #define pqueue priority_queue #define INF 0x3f3f3f3f #define ls (rt<<1) #define rs (rt<<1|1) int n,m; int head[MAXN],vis[MAXN],ptr=1; int mx[MAXN],mx2[MAXN],vx[MAXN],vx2[MAXN]; struct node{int y,next,val;}tree[MAXN<<2]; void init() { mem(head,-1); mem(vis,0); ptr = 1; } void add(int son,int fa,int val) { tree[ptr].y=son; tree[ptr].val=val; tree[ptr].next=head[fa]; head[fa]=ptr++; } void dfs(int root,int fa) { for(int i = head[root];i!=-1;i=tree[i].next) { int y = tree[i].y; if(y==fa) continue; dfs(y,root); if(mx2[root]<mx[y]+tree[i].val) { vx2[root] = y; mx2[root] = mx[y]+tree[i].val; if(mx2[root]>mx[root]) { swap(vx2[root],vx[root]); swap(mx2[root],mx[root]); } } } } void dfs2(int root,int fa) { for(int i = head[root];i!=-1;i=tree[i].next) { int y = tree[i].y; if(y==fa) continue; if(y == vx[root]) { if(mx2[root]+tree[i].val > mx2[y]) { mx2[y] = mx2[root]+tree[i].val; vx2[y] = root; if(mx2[y]>mx[y]) { swap(vx2[y],vx[y]); swap(mx2[y],mx[y]); } } } else { if(mx[root]+tree[i].val > mx2[y]) { mx2[y] = mx[root]+tree[i].val; vx2[y] = root; if(mx2[y]>mx[y]) { swap(vx2[y],vx[y]); swap(mx2[y],mx[y]); } } } dfs2(y,root); } } int main() { while(~sf("%d%d",&n,&m)) { init(); for(int i=1;i<n;i++) { int x,y,z;char ch[2]; sf("%d%d%d%s",&x,&y,&z,ch); add(x,y,z); add(y,x,z); } sf("%d",&K); getroot(1,0); solve(root); pf("%d\n",ans); } }
标签:
原文地址:http://www.cnblogs.com/qlky/p/5785897.html