关闭

hdu 2544(Dijkstra)

429人阅读 评论(0) 收藏 举报
分类:

题目链接:点击打开链接

题目分析:Dijkstra的简单应用,给出源点(1号节点)和目的地(n号节点),求出最短路径,自己结合教材YY的代码

题目小结:DIjkstra的无向图应用     

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define INF  0x3f3f3f
using namespace std;
int grid[105][105],ans=0;
void Dijkstra(int n)
{
    int min_dis,i,dis[105],w,v,s;
    bool intree[105];
    ans=0;
    for(i=1;i<=n;i++)
    {
        intree[i]=false;
        if(grid[1][i]==-1) dis[i]=INF;//先处理初始和源点相连的结点,若没有直接相连则赋值INF
        else dis[i]=grid[1][i];      //      
    }
    v=1;dis[1]=0,intree[1]=true;//intree 记录是否加入了新集合
    for( i=1; i<=n&&!intree[n];i++)//由于只求到n的最短路,所以其他可以省略
    {
        min_dis=INF;
        for(w=1;w<=n;w++)
           if(!intree[w])
             if(dis[w]<min_dis){v=w; min_dis=dis[w];}
        intree[v]=true;
        for(w=1;w<=n;w++)//用于更新到源点的最近距离
        {
            if(!intree[w]&&(min_dis+grid[v][w]<dis[w])&&grid[v][w]!=-1)
            {
                dis[w] = min_dis + grid[v][w] ;
            }
        }
    }
    ans=dis[n];
}
int main()
{
    freopen("in.txt","r",stdin);
   int n,m,i,a,b,c;
   while(scanf("%d%d",&n,&m)&&(n||m))
   {   memset(grid,-1,sizeof(grid));//表示ij 之间没有路径
       for(i=1;i<=m;i++)
       {
           scanf("%d%d%d",&a,&b,&c);
           grid[a][b]=grid[b][a]=c;
       }

       Dijkstra(n);
       printf("%d\n",ans);
   }
   return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:134217次
    • 积分:3153
    • 等级:
    • 排名:第10907名
    • 原创:180篇
    • 转载:38篇
    • 译文:0篇
    • 评论:17条
    最新评论
    proverb
    Do not spend all your time on training or studying – this way you will probably become very exhausted and unwilling to compete more. Whatever you do – have fun. Once you find programming is no fun anymore – drop it. Play soccer, find a girlfriend, study something not related to programming, just live a life – programming contests are only programming contests, and nothing more. Don’t let them become your life – for your life is much more interesting and colorful