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;
}
- HDU 1142 A Walk Through the Forest
- A Walk Through the Forest HDU 1142
- hdu 1142 A Walk Through the Forest
- Hdu-1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- HDU 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- 第二章:【UCHome二次开发】基础
- 3G时代,你准备好了吗?
- 基于apache的tomcat负载均衡和集群配置(基于mod_jk.so)
- apache开启gzip
- SVN禁止空日志
- hdu 1142 A Walk Through the Forest
- 获取一个控件相对于父窗口的坐标位置
- C++ map的基本操作和使用
- 两个obj文件怎么连接生成一个exe程序
- char *(*(**(*(*(*x[5])(int,float))[][12])(double))(short,long))[][173] ???
- 本地通知和推送通知编程指南(1)
- wrapper was not properly loaded first
- C++ Primer Plus学习:第八章 函数探幽(2)
- Interrupt--PIC--APIC