HDU - How far away ?(DFS+vector)

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Problem Description

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.


First line is a single integer T(T<=10), indicating the number of test cases.
  For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
  Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.


For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.

Sample Input

3 2
1 2 10
3 1 15
1 2
2 3

2 2
1 2 100
1 2
2 1

Sample Output


Problem solving report:

Description: 在一个村庄里有n个地方,这n个地方每两个之间都有一条唯一的双向道。进行m次询问,A到B的距离是多少?
Problem solving: 利用vector,把每条路的起点当数组的下标,终点作为数组里面存的内容,然后把权值用另一个数组存一下(定义一个结构体),在深搜里面就把每个数组里面存的终点作为新的起点进入新的递归。直到找到终点。

#include <vector> //动态数组的头文件
#include <stdio.h>
#include <string.h>
#define N 40010
using namespace std;
struct edge {
    int v, w;
int vis[N], temp;
vector <struct edge> a[N]; //定义一个结构体动态二维数组
void DFS(int x, int y, int sum)
    int i;
    if (x == y)
        printf("%d\n", sum);
        temp = 1;
        return ;
    int len = a[x].size(); //返回数组a[x]的元素个数
    if (!len || vis[x] || temp)
        return ;
    for (int i = 0; i < len; i++)
        vis[x] = 1;
        DFS(a[x][i].v, y, sum + a[x][i].w);
        vis[x] = 0;
int main()
    int t, m, n, u, v, w, x, y;
    scanf("%d", &t);
    while (t--)
        scanf("%d%d", &n, &m);
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i < n; i++)
            a[i].clear(); //清空动态数组 
        for (int i = 1; i < n; i++)
            scanf("%d%d%d", &u, &v, &w);
            a[u].push_back((edge){v, w});
            a[v].push_back((edge){u, w});
        for (int i = 0; i < m; i++)
            temp = 0;
            scanf("%d%d", &x, &y);
            DFS(x, y, 0);
    return 0;


©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503