HDU 2544 最短路 静态邻接表+优先队列 dijkstra

来源:互联网 发布:数字域名出售 编辑:程序博客网 时间:2024/05/16 09:20

http://acm.hdu.edu.cn/showproblem.php?pid=2544


早就想做这个最短路了,但是一直在那纠结着,这个题目可以用邻接矩阵做,但是邻接矩阵的限制很大点最多只能有300个,所以想想还是搞定邻接表好!!


静态邻接表关键是在于它的储存!!


#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>using namespace std;int n,m;int dist[105],hand[105],flag[105];     //flag为标记该点是否被走过,hand是静态邻接表的头,dist存放从1至n的最短距离#define INF 0xffffff;struct edges{int to,val,next;}edge[100005];                //edge数组为存放边的内容,为静态邻接表的一部分,next中存放的实质上是edge中id,但是这个id存放在hand数组中struct node{int s,law;friend bool operator<(const node &a,const node &b){if(a.law==b.law)return a.s>b.s;return a.law>b.law;}};                            //优先队列中的结构体priority_queue<node> Q;void dijkstra(){node temp,next;int i;while(!Q.empty()){temp=Q.top();Q.pop();if(flag[temp.s]==1)          //判断是否走过continue;flag[temp.s]=1;i=hand[temp.s];while(i!=-1){if(flag[edge[i].to]==0&&temp.law+edge[i].val<dist[edge[i].to])  //判断edge[i].to这个点有没有走过,并判断是否修改{dist[edge[i].to]=temp.law+edge[i].val;next.s=edge[i].to;next.law=dist[edge[i].to];Q.push(next);}i=edge[i].next;}}}int main(){int i;while(scanf("%d%d",&n,&m)!=EOF){if(n==0&&m==0)break;memset(hand,-1,sizeof(hand));memset(flag,0,sizeof(flag));for(i=1;i<=n;i++){dist[i]=INF;}int from,to,val;for(i=0;i<m;i++){scanf("%d%d%d",&from,&to,&val);edge[i*2].next=hand[from];hand[from]=i*2;edge[i*2].to=to;edge[i*2].val=val;edge[i*2+1].next=hand[to];hand[to]=i*2+1;edge[i*2+1].to=from;edge[i*2+1].val=val;                   //题目给出的边是双向的所以可以从to到from}dist[1]=0;node temp;temp.s=1;temp.law=0;Q.push(temp);dijkstra();printf("%d\n",dist[n]);}return 0;}


原创粉丝点击