hdu 1142 A Walk Through the Forest

最短路+记忆化搜索

#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;

}  

 

你可能感兴趣的:(REST)