hdu1546(最短路SPFA+priority_queue)

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

 

简单的最短路问题,不过看起来数据不少,所以用了priority_queue来优化SPFA;

 

好吧,不得不承认,自己很多时候太不小心了~

RE了3次,最后才发现接受输入的w[]数组开小了,从16到32再到52再到108......

 

3755958 2011-04-03 01:05:02 Accepted 1546 31MS 440K 1826 B C++ ㄉ ㄉ

 

#include<stdio.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #include<queue> using namespace std; #define M 1008 #define INF 0x7fffffff typedef struct{//输入摘要 int head,tail,time; }Idiom; typedef struct{//静态邻接表 int u,v,c; int next; }Edge; typedef struct talQNode{//优先队列元素 int v,dis; bool operator < (const talQNode &a) const { return a.dis<dis; } }QNode; priority_queue<QNode>q; Edge edge[108*M];//边 Idiom id[M]; int head[M];//头 int dis[M]; bool inq[M]; int n,e; int ToNum(char c) { if(isdigit(c)) return c-'0'; return c-'A'+10; } void ToElem(int c,char *w,int ix) { int i,l=strlen(w); id[ix].time=c; id[ix].head=id[ix].tail=0; for(i=0;i<4;i++){ id[ix].head*=16; id[ix].head+=ToNum(w[i]); id[ix].tail*=16; id[ix].tail+=ToNum(w[l-4+i]); } } void AddEdge(int u,int v,int c) {//添加边 edge[e].u=u;edge[e].v=v;edge[e].c=c; edge[e].next=head[u];head[u]=e++; } void SPFA() {//SPFA求最短路过程,用priority_queue优化 QNode cur,next; int u,v,tmp; for(u=0;u<n;u++){ inq[u]=false; dis[u]=INF; } dis[0]=0; inq[0]=true; cur.dis=0;cur.v=0; q.push(cur); while(!q.empty()){ cur=q.top();q.pop(); inq[cur.v]=false;u=cur.v; for(tmp=head[u];tmp!=-1;tmp=edge[tmp].next){ v=edge[tmp].v; if(dis[v]-dis[u]>edge[tmp].c){ dis[v]=dis[u]+edge[tmp].c; if(!inq[v]){ inq[v]=true; next.v=v; next.dis=dis[v]; q.push(next); } } } } } int main() {//最短路 hdu1546 char w[108]; int c,i,j; while(scanf("%d",&n),n){ for(i=0;i<n;i++){ scanf("%d%s",&c,w); ToElem(c,w,i); } e=0; memset(head,-1,sizeof(head)); for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i==j) continue; if(id[i].tail==id[j].head) AddEdge(i,j,id[i].time); } } SPFA(); if(dis[n-1]==INF) dis[n-1]=-1; printf("%d/n",dis[n-1]); } return 0; }

你可能感兴趣的:(hdu1546(最短路SPFA+priority_queue))