码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1142 A Walk Through the Forest

时间:2015-05-23 15:27:09      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

最短路+记忆化搜索

#include<cstdio>
#include<vector>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

const int maxn = 1003;
const int INF = 0x3f3f3f3f;
vector<int>ljb[maxn];
int jz[maxn][maxn], dist[maxn], flag[maxn];
int u[maxn * 1000], v[maxn * 1000], c[maxn * 1000], dp[maxn];
int n, m, ans;

void spfa()
{
    int i;
    memset(flag, 0, sizeof(flag));
    queue<int>Q; Q.push(2); flag[2] = 1;
    for (i = 0; i <= n; i++) dist[i] = INF;
    dist[2] = 0;
    while (!Q.empty())
    {
        int h = Q.front(); Q.pop(); flag[h] = 0;
        for (i = 0; i < ljb[h].size(); i++)
        {
            if (jz[h][ljb[h][i]] != INF)
            {
                if (dist[h] + jz[h][ljb[h][i]] < dist[ljb[h][i]])
                {
                    dist[ljb[h][i]] = dist[h] + jz[h][ljb[h][i]];
                    if (flag[ljb[h][i]] == 0)
                    {
                        flag[ljb[h][i]] = 1;
                        Q.push(ljb[h][i]);
                    }
                }
            }
        }
    }
}

int dfs(int wei)
{
    int i;
    if (dp[wei]) return dp[wei];
    if (wei == 2) return 1;
    for (i = 0; i < ljb[wei].size(); i++)
        dp[wei] = dp[wei] + dfs(ljb[wei][i]);
    return dp[wei];
}

int main()
{
    int i, j;
    while (scanf("%d", &n))
    {
        if (n == 0) break;
        scanf("%d", &m);

        for (i = 0; i <= n; i++)
        {
            for (j = 0; j <= n; j++)
            {
                if (i == j) jz[i][j] = 0;
                else jz[i][j] = INF;
            }
        }

        for (i = 1; i <= m; i++)
        {
            scanf("%d%d%d", &u[i], &v[i], &c[i]);
            if (c[i] < jz[u[i]][v[i]])
            {
                jz[u[i]][v[i]] = c[i];
                jz[v[i]][u[i]] = c[i];
                ljb[u[i]].push_back(v[i]);
                ljb[v[i]].push_back(u[i]);
            }
        }
        spfa();

        for (i = 0; i <= n; i++) ljb[i].clear();
        for (i = 1; i <= m; i++)
        {
            if (dist[u[i]] > dist[v[i]]) ljb[u[i]].push_back(v[i]);
            if (dist[u[i]] < dist[v[i]]) ljb[v[i]].push_back(u[i]);
        }
        ans = 0; memset(dp, 0, sizeof(dp)); dfs(1);
        printf("%d\n", dp[1]);
    }
    return 0;
}  

 

hdu 1142 A Walk Through the Forest

标签:

原文地址:http://www.cnblogs.com/zufezzt/p/4524074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!