Tan Songsong's travel plans
Time limit:3000/1000ms (java/others) Memory limit:65535/65535kb (java/others)Submit Status
Tan Songsong is a person who loves to travel, he loves traveling very much, even if the body is emptied also must insist on traveling. The Mew Clam Kingdom consists of n cities, connected by the N-1 road, each with a CI-length, so that any two cities can reach each other. Tan Songsong has m travel plans, each tour plan has a starting point AI, an end point bi, so Tan Songsong wants to know how short the shortest path from the starting point to the endpoint is for each travel plan. Input
The first row of two integers N (2≤n≤100000,), M (1≤m≤100000), represents the number of cities, Tan Songsong the number of travel plans.
Next N-1 line, three integers per line li,ri,ci (1≤ci≤10000), indicates that there is a CI-length road between the city of Li and the RI number city.
Next m line, two integers per line ai,bi the start and end of the tour plan. Output
The output m line, which represents the shortest distance per travel plan. Sample input and output
Sample Input |
Sample Output |
7 6
1 2 5
1 3 4
3 7 7
2 4 4
2 5 3
5 6 2
1 2
4 7
6 3
3 2 5
4
7 6 |
5
9
7
|
The topic says that all points are interconnected, so consider using LCA (the nearest common ancestor) to solve the problem. LCA Knowledge Point: http://blog.csdn.net/cxllyg/article/details/7635992 Here I use the second way to do, the third kind of temporarily not read. The code is as follows:
#include <cstdio> #include <vector> #include <algorithm> using namespace std;
int n,m;
struct node {int to,p;};
Vector <node> v[100010]; int depth[100010],cost[100010],vis[100010],fa[100010];//Depth Weight tag access parent node void DFS (int x,int dep) {for (int i=0;i<v[
X].size (); i++) {int to=v[x][i].to;
int P=V[X][I].P;
if (vis[to]==1) {continue;
} depth[to]=dep+1;
Cost[to]=p;
Fa[to]=x;
Vis[to]=1;
DFS (TO,DEP+1);
}} int main () {scanf ("%d%d", &n,&m);
node tmp;
for (int i=1;i<n;i++) {int s,e,p;
scanf ("%d%d%d", &s,&e,&p);
Tmp.to=s;
Tmp.p=p;
V[e].push_back (TMP);
Tmp.to=e;
V[s].push_back (TMP);
} vis[1]=1;
DFS (1,0);//Construction tree while (m--) {int x, y;
scanf ("%d%d", &x,&y);
int ans=0;
while (Depth[x]>depth[y])//move x and Y to the same height {ans=ans+cost[x];
X=FA[X];
} while (Depth[x]<depth[y])//move x and Y to the same height {ans=ans+cost[y];
Y=fa[y]; } while (x!=y)//x and y go in parallel {ans=ans+cost[x]+cost[y];
X=FA[X];
Y=fa[y];
} printf ("%d\n", ans);
} return 0; }