Travel(两点之间求路的旅行)

描述

There are N cities in this country, and some of them are connected by roads. Given two cities, can you find the shortest distance between them?

输入

The first line contains the number of test cases, then some test cases followed.

The first line of each test case contain two integers N and M (3 ≤ N ≤ 1000, M ≥ 0), indicating the number of cities and the number of roads. The next line contain two numbers S and T (ST), indicating the start point and the destination. Each line of the following M lines contain three numbers Ai, Bi and Ci (1 ≤ Ai,BiN, 1 ≤ Ci ≤ 1000), indicating that there is a road between city Ai and city Bi, whose length is Ci. Please note all the cities are numbered from 1 to N.

The roads are undirected, that is, if there is a road between A and B, you can travel from A to B and also from B to A.

输出

Output one line for each test case, indicating the shortest distance between S and T. If there is no path between them, output -1.

样例输入

2
3 3
1 3
1 2 10
2 3 20
1 3 50
3 1
1 3
1 2 10

样例输出

30
-1


代码如下:
#include<iostream>
#include<cstdio>

using namespace std;

const int maxn = 9999999;
int e[1005][1005];
int book[1005];
int strat,endn;
int n,m;
int minn;
///cnt表示当前的位置,num表示走过的距离
void dfs(int cnt,int num)
{
    ///剪枝1,表示他可以不要继续找下去了。
    if(num>minn)
    {
        return ;
    }

    ///表示找到了。
    if(cnt==endn)
    {
        if(minn>num)
        {
            minn = num;
        }
        return ;
    }

    ///表示递归寻找
    for(int i=1; i<=n; i++)
    {
        if(e[cnt][i]!=maxn && book[i] == 0)
        {
            book[i] = 1;
            dfs(i,num+e[cnt][i]);
            book[i] = 0;
        }
    }
    return ;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        scanf("%d%d",&strat,&endn);
        for(int i=1; i<=n; i++)
        {
            book[i]=0;
            for(int j=1; j<=n; j++)
            {
                if(i==j) e[i][j]=0;
                else e[i][j] = maxn;
            }
        }
        for(int i=0; i<m; i++)
        {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            e[x][y] = z;
            e[y][x] = z;
        }
        minn = maxn;
        book[strat]=1;
        dfs(strat,0);
        if(minn==maxn)
            minn = -1;
        printf("%d\n",minn);
    }
    return 0;
}

posted @ 2017-08-11 16:20  让你一生残梦  阅读(186)  评论(0编辑  收藏  举报