dijkstra 算法

我什么都说不出来了

 

 

 

 

GOOD LUCKY

 

 

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

const int maxn =10100;

int g[maxn][maxn],n,m;
int dis[maxn],status[maxn];


void dij(int start){
    memset(status,0,sizeof(status));
    memset(dis,0x3f,sizeof(dis));
    dis[start]=0;
    status[start] = 1;
    for(int ti=1;ti<=n;++ti){
        int pick=-1;
        for(int i=1;i<=n;++i){
            if(status[i] == 1){
                if(pick== -1|| dis[i]< dis[pick])
                pick=i;
            }
        }
        if(pick== -1){
        break;
        }
        status[pick] = 2;
        for(int i=1;i<=n;++i){
            if(status[i] ==0|| status[i] == 1){
                if(g[pick][i] != -1){
                    status[i] = 1;
                    dis[i]=min(dis[i],dis[pick]+g[pick][i]);
                } 
            }
        }
    }
}



int main(){
    memset(g,-1,sizeof(g));

    cin>>n>>m>>s;
    for(int i=1;i<=m;++i){
        int x,y,z;
        cin>>x>>y>>z;
        g[x][y]=g[y][x]=z;
    }
    dij(s);
    for(int i=1;i<=n;++i)
    {
        if(dis[i]== -1 )
        cout<<2147483647<<" ";
        else
        cout<<dis[i]<<" ";
    }
}

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int vis[510000];
int head[510000];
int p;
struct b{
    int f;
    int to;
    int v;
    int next;
}bian[500005]; 

int n,m,s;
int dis[510000];
int x,y,z;

void add(int f,int t,int v){
    p++;
    bian[p].next=head[f];
    bian[p].f=f;
    bian[p].to=t;
    bian[p].v=v;
    head[f]=p;
}
int main(){
    memset(dis,0x3f3f,sizeof(dis));
    cin>>n>>m>>s;
    for(int i=1;i<=m;++i){
        cin>>x>>y>>z;
        add(x,y,z);
    }
    dis[s]=0;
    for(int i=1;i<=n;++i){
        int minn=0x3f3f;
        int mm;
        for(int j=1;j<=n;++j){
            if(!vis[j]&&dis[j]<=minn){
                minn=dis[j];
                mm=j;
            }
        }
        vis[mm]=1;
        {
            for(int k=head[mm];k;k=bian[k].next){
                int v=bian[k].to;
                dis[v]=min(dis[v],dis[mm]+bian[k].v);
            }
        }
    }
    for(int i=1;i<=n;++i)
    if(dis[i]>=0x3f3f)
    cout<<"2147483647 ";
    else
    cout<<dis[i]<<" ";
    return 0;
}

 

posted @ 2019-03-17 16:07  Simex  阅读(272)  评论(0编辑  收藏  举报