Note that this question may be Crash. Use the Color [] = 0 1 2 solution, instead of using Parent [] to limit a tree.
You can also use
[Cpp]
# Pragma comment (linker, "/STACK: 1000000000 ")
But not recommended
Code:
[Cpp]
# Include <iostream>
# Include <stdlib. h>
# Include <stdio. h>
# Include <string. h>
Using namespace std;
# Deprecision max 50010
# Define max2 75010
Int parent [max]; // indicates that the undirected direction is changed to directed.
Int father [max]; // check the nodes in the set.
Int ancestor [max]; // ancestor node in LCA
Int color [max]; // mark of Deep Search
Int dis [max]; // distance from the root node
Int ran [max]; // check the height of the root node in the forest.
Int quex [max2]; // The queried x
Int quey [max2]; // y of the query
Int final [max2]; // ancestor of two vertices
Struct edge
{
Int y;
Int w;
Edge * next;
Edge (int y1, int w1, edge * next1)
{
Y = y1;
W = w1;
Next = next1;
}
} * E [max];
Struct que
{
Int y;
Int n;
Que * next;
Que (int y1, int n1, que * next1)
{
Y = y1;
N = n1;
Next = next1;
}
} * Q [max2];
Void makeset (int I)
{
Father [I] = I;
Ran [I] = 1;
}
Int findset (int I)
{
If (father [I] = I)
{
Return I;
}
Return father [I] = findset (father [I]);
}
Int unionset (int x, int y)
{
Int a = findset (x );
Int B = findset (y );
If (a = B)
{
Return 0;
}
Else if (ran [a]> ran [B])
{
Father [B] =;
Ran [a] + = ran [B];
}
Else
{
Father [a] = B;
Ran [B] + = ran [a];
}
Return 0;
}
Void lca (int u)
{
Color [u] = 1;
Makeset (u );
Ancestor [u] = u;
For (edge * e = E [u]; e = e-> next)
{
Int v = e-> y;
Int wtemp = e-> w;
If (color [v] = 0)
{
Dis [v] = dis [u] + wtemp;
Lca (v );
Unionset (u, v );
Ancestor [findset (u)] = u;
}
}
Color [u] = 2;
For (que * q = Q [u]; q = q-> next)
{
Int v = q-> y;
If (color [v] = 2)
{
Final [q-> n] = ancestor [findset (v)];
}
}
}
Int main ()
{
# Ifndef ONLINE_JUDGE
Freopen ("in.txt", "r", stdin );
# Endif
Int n, m;
Memset (E, 0, sizeof (E ));
Memset (Q, 0, sizeof (Q ));
Memset (final, 0, sizeof (final ));
Scanf ("% d", & n );
For (int I = 0; I <n-1; I ++)
{
Int a, B, c;
Scanf ("% d", & a, & B, & c );
E [a] = new edge (B, c, E [a]);
E [B] = new edge (a, c, E [B]);
}
Parent [0] =-1; // lca starts from 0
Memset (dis, 0, sizeof (dis ));
Memset (color, 0, sizeof (color ));
Scanf ("% d", & m );
For (int I = 0; I <m; I ++)
{
Int x, y;
Scanf ("% d", & x, & y );
Quex [I] = x;
Quey [I] = y;
Q [x] = new que (y, I, Q [x]);
Q [y] = new que (x, I, Q [y]);
}
Lca (0 );
For (int I = 0; I <m; I ++)
{
Printf ("% d \ n", dis [quex [I] + dis [quey [I]-2 * dis [final [I]);
}
Return 0;
}