首页 > 代码库 > 1874畅通工程续(dijkstra算法)

1874畅通工程续(dijkstra算法)

迷糊了好长时间,一开始有好多不理解的,到现在还没完全理清,不过比上午好多了,感觉不错,

#include<iostream>#include<cstring>#include<algorithm>#include<queue>using namespace std;int n,m;const int maxn = 210;const int maxm = 2010;const int inf = 0x3f3f3f3f;typedef pair<int,int> pii;int v[maxm],next[maxm],w[maxm];int first[maxn],d[maxn],e;void init(){    e =0;    memset(first,-1,sizeof(first));}void add_edge(int a,int b,int c){    v[e] = b;    next[e] =first[a];    w[e] =c;    first[a] = e++;}void dijkstra(int src){    priority_queue<pii,vector<pii>,greater<pii> >q;    memset(d,-1,sizeof(d));    d[src] = 0;    q.push(make_pair(0,src));    while(!q.empty())    {        //while(!q.empty()/*&&q.top().first>d[q.top().second]*/)            //q.pop();        //if(q.empty())break;        int u = q.top().second;        q.pop();        for(int i = first[u];i!=-1;i= next[i])        {            if(d[v[i]]==-1||d[v[i]]>d[u]+w[i])            {                d[v[i]] = d[u]+w[i];                q.push(make_pair(d[v[i]],v[i]));            }        }    }}int main(){    while(cin >> n>> m)    {        init();        int a,b,c;        for(int i =0;i < m;i++)        {            cin >> a>> b>> c;            add_edge(a,b,c);            add_edge(b,a,c);        }        int x,y;        cin >> x>> y;        dijkstra(x);        if(d[y]!= inf)cout<< d[y]<< endl;        else cout<< "-1"<< endl;    }    return 0;}