Dijstra的greedy简单实现

来源:互联网 发布:java高级流和低级流 编辑:程序博客网 时间:2024/05/22 08:49

算法本意重于数据结构。

#include <iostream>#include <cstring>#include <limits>using namespace std;//The simpler,the betterconst int maxn=10000;const int inf=100000; // at first I wana use limits::max,but add operation causing overflow,so UDFint book[maxn];int g[maxn][maxn]; //DON'T use complex data structure making you confuing before really understand the origial ideaint dist[maxn];int n,m;void dij(int cur){int min,relaxIdx;//relax variabledist[cur]=0;book[cur]=1; int t=n;//O(n^2)while(--t){min = numeric_limits<int>::max();for(int i=1 ; i<= n ; ++i )//find the shortest pointif(g[cur][i]!=inf && g[cur][i]<min && book[i]==0){min=g[cur][i];relaxIdx = i;}dist[relaxIdx] = min;//update the distance to final statebook[relaxIdx] = 1;  //add to the fianl setfor(int i=1 ; i<=n ; ++i)//relaxing the distance using relaxIdxif(g[cur][i]>g[cur][relaxIdx]+g[relaxIdx][i])g[cur][i]=g[cur][relaxIdx]+g[relaxIdx][i];}//Output the resultfor(int i=1; i<=n ; ++i)cout<<dist[i]<<" ";}int main() {// your code goes herecin>>n>>m;int a,b,c;int start=1;//initialize the graph;for(int i=1; i<= n ; ++i)for(int j=1;j<=n;++j)g[i][j]=inf;//input graphfor(int j=0; j<m ; j++){cin>>a>>b>>c;g[a][b]=c;}//initialize the distance arrayfor(int i= 1 ; i<=n ; ++i)if(g[start][i]!=inf)dist[i]=g[start][i];dij(start);return 0;}


0 0
原创粉丝点击