hdu 1142 A Walk Through the Forest

来源:互联网 发布:安卓源码编译 编辑:程序博客网 时间:2024/05/17 16:45

一道求最短路径的题目,和其他的区别在于,这道题目要求最短路径的条数而不是距离!

网上大多采用记忆化搜索的办法进行路径的搜索!用Dijkstra算法做的!

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=1002;
const int inf=10000000;

bool s[maxn];
int dp[maxn],dist[maxn];
int map[maxn][maxn];
int n,m;

void Dijkstra(int v0)//从顶点v0开始找SP
{
   int i,j,k;
  
   //1、将距离更改为从v0到其他点的距离
   for(int i=1;i<=n;i++)
   {
      dist[i]=map[v0][i];s[i]=0;
   }
   s[v0]=1;dist[v0]=0;//顶点v0加入到顶点集合S
   for(i=1;i<=n-1;i++)//从顶点v0确定n-1条最短路径
   {
      int min=inf,u=v0;
      for(int j=1;j<=n;j++)
         if(!s[j]&&dist[j]<min)
         {
            u=j;
            min=dist[j];
         }
      s[u]=1;
     
      for(k=1;k<=n;k++)
         if(!s[k]&&(dist[k]>dist[u]+map[u][k])&&map[u][k]<inf)
            dist[k]=dist[u]+map[u][k];
   }
}

//求最短路径的条数,记忆化搜索
int dfs(int x)
{
   if(x==2) return 1;
   if(dp[x]!=-1) return dp[x];
   dp[x]=0;
   for(int i=1;i<=n;i++)
      if(map[x][i]!=inf && dist[i]<dist[x])
         dp[x]+=dfs(i);
   return dp[x];
}

int main()
{
   int a,b,c;
   while(scanf("%d",&n),n)
   {
      for(int i=1;i<=n;i++)
         for(int j=1;j<=n;j++)
            map[i][j]=inf;
      scanf("%d",&m);
      while(m--)
      {
         scanf("%d%d%d",&a,&b,&c);
         map[a][b]=map[b][a]=min(c,map[a][b]);
      }
      Dijkstra(2);
      memset(dp,-1,sizeof(dp));
      //dp[1]=0;
      cout<<dfs(1)<<endl;
   }
  
   return 0;
}