HDU-1142-A Walk Through the Forest

ACM模版

描述

描述

题解

dij+dfs,先通过dij预处理一遍求终点的单源最短路,然后再记忆化dfs,最终获取有多少条路可供选择。

代码

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

/*
 *  单源最短路径,Dijkstra算法,邻接矩阵形式,复杂度为O(n^2)
 *  求出源beg到所有点的最短路径,传入图的顶点数和邻接矩阵cost[][]
 *  返回各点的最短路径lowcost[],路径pre[],pre[i]记录beg到i路径上的父节点,pre[beg] = -1
 *  可更改路径权类型,但是权值必须为非负,下标0~n-1
 */
const int MAXN = 1010;
const int INF = 0x3f3f3f3f; //  表示无穷
bool vis[MAXN];
int pre[MAXN];

void Dijkstra(int cost[][MAXN], int lowcost[], int n, int beg)
{
    for (int i = 0; i < n; i++)
    {
        lowcost[i] = INF;
        vis[i] = false;
        pre[i] = -1;
    }
    lowcost[beg] = 0;
    for (int j = 0; j < n; j++)
    {
        int k = -1;
        int min = INF;
        for (int i = 0; i < n; i++)
        {
            if (!vis[i] && lowcost[i] < min)
            {
                min = lowcost[i];
                k = i;
            }
        }
        if (k == -1)
        {
            break;
        }
        vis[k] = true;
        for (int i = 0; i < n; i++)
        {
            if (!vis[i] && lowcost[k] + cost[k][i] < lowcost[i])
            {
                lowcost[i] = lowcost[k] + cost[k][i];
                pre[i] = k;
            }
        }
    }
}

int cost[MAXN][MAXN];
int lowcost[MAXN];
int paths[MAXN];

int dfs(int s, int n)
{
    if (paths[s])   //  记忆化搜索
    {
        return paths[s];
    }
    if (s == 1)
    {
        return 1;   //  到达终点
    }

    int count = 0;
    for (int i = 0; i < n; i++)
    {
        if (cost[s][i] != INF && lowcost[i] < lowcost[s])
        {
            count += dfs(i, n);
        }
    }
    paths[s] = count;

    return paths[s];
}

int main(int argc, const char * argv[])
{
    int N, M;
    while (cin >> N, N != 0)
    {
        cin >> M;
        memset(cost, 0x3f, sizeof(cost));
        memset(paths, 0, sizeof(paths));
        int u, v, w;
        for (int i = 0; i < M; i++)
        {
            scanf("%d%d%d", &u, &v, &w);
            u--;
            v--;
            if (w < cost[u][v])
            {
                cost[u][v] = cost[v][u] = w;
            }
        }

        Dijkstra(cost, lowcost, N, 1);

        int count = dfs(0, N);
        cout << count << '\n';
    }

    return 0;
}

参考

《最短路》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值