1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std; inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; } const int maxn=200005; struct Edge { int from,to,dist; Edge(int u=0,int v=0,int d=0):from(u),to(v),dist(d) {} bool operator < (const Edge& b) const { return dist>b.dist; } }; vector<Edge>edge; vector<int>edges[maxn]; void AddEdge(int x,int y) { edges[x].push_back(y); } int First[maxn],Last[maxn],Size[maxn],father[maxn],Value[maxn],n,q,cnt,step=0; void Dfs(int Now) { First[Now]=++step; Size[Now]=Now<=n; for(auto &Next:edges[Now]) { Dfs(Next); Size[Now]+=Size[Next]; } Last[Now]=step; } struct BIT { int c[maxn]; #define Lowbit(x) x&(-x) void add(int x,int v) { for(int i=x; i<=2*n; i+=Lowbit(i))c[i]+=v; } int sum(int x) { int ans=0; for(int i=x; i>=1; i-=Lowbit(i))ans+=c[i]; return ans; } } bit; void Update(int x,int y) { bit.add(First[x],y); bit.add(Last[x]+1,-y); } void Clear() { for(int i=1; i<=2*n; i++)edges[i].clear(); edge.clear(); for(int i=1; i<=2*n; i++)father[i]=i; step=0; memset(bit.c,0,sizeof(bit.c)); } int Get_Father(int x) { if(father[x]==x)return x; else return father[x]=Get_Father(father[x]); } int main() { q=Get_Int(); for(int t=1; t<=q; t++) { cnt=n=Get_Int(); Clear(); for(int i=1; i<n; i++) { int x=Get_Int(),y=Get_Int(),v=Get_Int(); edge.push_back(Edge(x,y,v)); } sort(edge.begin(),edge.end()); for(auto &e:edge) { int fx=Get_Father(e.from),fy=Get_Father(e.to); Value[++cnt]=e.dist; father[fx]=father[fy]=cnt; AddEdge(cnt,fx); AddEdge(cnt,fy); } Dfs(cnt); for(int i=n+1; i<=cnt; i++) { Update(edges[i][0],Size[edges[i][1]]*Value[i]); Update(edges[i][1],Size[edges[i][0]]*Value[i]); } int ans=0; for(int i=1; i<=n; i++)ans=max(ans,bit.sum(First[i])); printf("Case %d: %d\n",t,ans); } return 0; }
|