hdu1142 A Walk Through the Forest(spfa+记忆化搜索)


http://acm.hdu.edu.cn/showproblem.php?pid=1142

题意:n个点m个关系,起点是1,终点是2(家)。这里主人公每当选择路A到B时有一个要求:“if there exists a route from B to his home that is shorter than any possible route from A”,翻译为家到B的最短路小于家到A的最短路,其实就是我们直观的想法,每走一步就要离家近一点。问满足这样条件路径的条数有多少。


思路:首先每次选择路的时候比较的是到2的最短路,那么我们就求从2到所有节点的单源最短路。然后我们找满足这样条件的路,注意这条件在松弛过后的图中使用,其实就是贪心算法,求出的必定是最短路。接着用记忆化搜索保存路径条数,起点的cnt值就是最多的条数。


#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>

using namespace std;

typedef long long LL;

const int N = 1005;
const int INF = 0x3f3f3f3f;

int dis[N], G[N][N], cnt[N], n;//cnt保存满足条件路径的条数
bool vis[N];

void spfa(int s)
{
    memset(vis, 0, sizeof(vis));
    queue<int>que;
    for(int i = 1; i <= n; i++)
        dis[i] = INF;
    dis[s] = 0;
    vis[s] = true;
    que.push(s);
    while(!que.empty())
    {
        int now = que.front();
        que.pop();
        vis[now] = false;
        for(int i = 1; i <= n; i++)
        {
            if(dis[now]+G[now][i]<dis[i])
            {
                dis[i] = dis[now]+G[now][i];
                if(!vis[i])
                {
                    vis[i] = true;
                    que.push(i);
                }
            }
        }
    }
}


int dfs(int s)
{
    if(s == 2) return cnt[2] = 1;
    if(cnt[s] >= 0) return cnt[s];
    else
    {
        int sum = 0;
        for(int i = 1; i <= n; i++)
        {
            if(G[s][i] != INF && dis[i]<dis[s])
                sum+=dfs(i);
        }
        return cnt[s] = sum;
    }
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    int m, s, e, w;
    while(~scanf("%d", &n))
    {
        if(n == 0) break;
        scanf("%d", &m);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
            {
                if(i == j) G[i][j] = 0;
                else G[i][j] = INF;
            }
        for(int i = 1; i <= m; i++)
        {
            scanf("%d%d%d", &s, &e, &w);
            G[s][e] = G[e][s] = w;
        }
        spfa(2);
        memset(cnt, -1, sizeof(cnt));
        printf("%d\n", dfs(1));
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值