题目大意:给定一棵树(直接给树,不是给图求生成树!),求每条边权值*两边点数之差的和
BFS水过即可
其实DFS也能过。。。系统栈可能有些不充裕,我们可以利用内嵌汇编手动开大系统栈 详见代码
这题读入优化可以优化掉4s左右
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define stack_size (20001000) #define M 1001001 using namespace std; typedef long long ll; struct abcd{ int to,f,next; }table[M<<1]; int head[M],tot; int n,fa[M],f[M],siz[M],q[M],r,h; ll ans; int stack[stack_size],bak; void DFS(int x) { int i; siz[x]=1; for(i=head[x];i;i=table[i].next) { if(table[i].to==fa[x]) continue; fa[table[i].to]=x; f[table[i].to]=table[i].f; DFS(table[i].to); siz[x]+=siz[table[i].to]; } ans+=(ll)abs(siz[x]+siz[x]-n)*f[x]; } void CallDFS() { __asm__ __volatile__ ( "mov %%esp,%0\n" "mov %1,%%esp\n" :"=g"(bak) :"g"(stack+stack_size-1) : ); DFS(1); __asm__ __volatile__ ( "mov %0,%%esp\n" : :"g"(bak) : ); } inline int getc() { static const int L = 1 << 15; static char buf[L], *S = buf, *T = buf; if (S == T) { T = (S = buf) + fread(buf, 1, L, stdin); if (S == T) return EOF; } return *S++; } inline int getint() { int c; while(!isdigit(c = getc()) && c != '-'); bool sign = c == '-'; int tmp = sign ? 0 : c - '0'; while(isdigit(c = getc())) tmp = (tmp << 1) + (tmp << 3) + c - '0'; return sign ? -tmp : tmp; } void Add(int x,int y,int z) { table[++tot].to=y; table[tot].f=z; table[tot].next=head[x]; head[x]=tot; } int main() { int i,x,y,z; cin>>n; for(i=1;i<n;i++) { x=getint(); y=getint(); z=getint(); Add(x,y,z); Add(y,x,z); } CallDFS(); cout<<ans<<endl; }
时间: 2024-10-12 10:47:44