• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
FightingForWorldFinal
博客园    首页    新随笔    联系   管理    订阅  订阅

dijkstra

#define DeBUG
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <set>
#include <sstream>
#include <map>
#include <bitset>
using namespace std ;
#define zero {0}
#define INF 2000000000
#define EPS 1e-6
typedef long long LL;
const double PI = acos(-1.0);
inline int sgn(double x)
{
    return fabs(x) < EPS ? 0 :(x < 0 ? -1 : 1);
}

/**
 * [Dijkstra description]
 * @param  mp   权值矩阵,从1开始 
 * @param  n    点数
 * @param  s    起始点
 * @param  t    终点
 * @param  path 起始点到各点的路(前驱)
 * @return      起点到终点的最短长度
 */
int Dijkstra(int mp[][100],int n,int s,int t, int path[])
{
    int i,j,w,minc;
    bool visit[100];
    int price[100];
    for(i=1; i<=n; i++) 
        visit[i]=false;
    for(i=1; i<=n; i++)
    {
        price[i]=mp[s][i];
        path[i]=s;
    }
    visit[s]=true;
    price[s]=0;
    //path[s]=0;

    for(i=1; i<n; i++)
    {
        minc=INF;
        w=0;
        for(j=1; j<=n; j++)
            if((visit[j]==false)&&(minc>=price[j]))
            {
                minc=price[j];
                w=j;
            }
        visit[w]=true;
        for(j=1; j<=n; j++)
            if((visit[j]==false)&&(mp[w][j]!=INF)&&(price[j]>price[w]+mp[w][j]))
            {
                price[j]=price[w]+mp[w][j];
                path[j]=w;
            }
    }
    return price[t];
}
void init(int mp[][100],int n)
{
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            mp[i][j]=INF;
        }
    }
}
int main()
{
#ifdef DeBUGs
    freopen("C:\\Users\\Sky\\Desktop\\1.in","r",stdin);
#endif
    int n,m;
    int mp[100][100];
    int path[100];
    while(scanf("%d%d",&n,&m)+1)
    {
        init(mp,n);
        int a,b;
        for(int i=1; i<=m; i++)
        {
            scanf("%d%d",&a,&b);
            mp[a][b]=1;
            mp[b][a]=1;
        }
        int s=1;
        int t=7;
        int value=Dijkstra(mp,n,s,t,path);
        for(int i=1;i<=n;i++)
        {
            int k=i;
            while(k!=s)
            {
                printf("%d<--",k);
                k=path[k];
            }
            printf("%d\n",s);
        }
    //    printf("%d\n",s);
        printf("%d\n", value);
    }
    return 0;
}
/*
7 7
1 2
2 3
3 4
1 5
5 7
5 6
2 7
*/
View Code

 

 

posted @ 2013-12-08 13:19  Sky-J  阅读(189)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3