#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
#define Size 10010
#define Max 99999999
struct ele
{
int to;
int w;
int next;
}p[2*Size];
struct Ele
{
int len;
int num;
friend bool operator <(Ele x,Ele y)
{
return x.len>y.len;
}
};
int head[Size];
int lowcost[Size];
bool Mark[Size];
int e;
int n,m;
void Add(int x,int y,int z)
{
p[e].to=y;
p[e].w=z;
p[e].next=head[x];
head[x]=e++;
}
void Dij(int x)
{
int i;
for(i=1;i<=n;i++)
{
lowcost[i]=Max;
Mark[i]=false;
}
priority_queue<Ele>p1;
lowcost[1]=0;
Ele point,it;
point.len=0;
point.num=1;
p1.push(point);
while(!p1.empty())
{
// printf("11111\n");
it=p1.top();
p1.pop();
x=it.num;
if(Mark[x])
continue;
Mark[x]=true;
for(i=head[x];i!=-1;i=p[i].next)
if(!Mark[p[i].to]&&lowcost[p[i].to]>lowcost[x]+p[i].w)
{
lowcost[p[i].to]=lowcost[x]+p[i].w;
it.len=lowcost[p[i].to];
it.num=p[i].to;
p1.push(it);
}
}
}
int main()
{
int i;
int x,y,z;
while(scanf("%d%d",&n,&m),n&&m)
{
e=1;
memset(head,-1,sizeof(head));
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
Add(x,y,z);
Add(y,x,z);
}
Dij(1);
printf("%d\n",lowcost[n]);
}
return 0;
#include<queue>
#include<string.h>
using namespace std;
#define Size 10010
#define Max 99999999
struct ele
{
int to;
int w;
int next;
}p[2*Size];
struct Ele
{
int len;
int num;
friend bool operator <(Ele x,Ele y)
{
return x.len>y.len;
}
};
int head[Size];
int lowcost[Size];
bool Mark[Size];
int e;
int n,m;
void Add(int x,int y,int z)
{
p[e].to=y;
p[e].w=z;
p[e].next=head[x];
head[x]=e++;
}
void Dij(int x)
{
int i;
for(i=1;i<=n;i++)
{
lowcost[i]=Max;
Mark[i]=false;
}
priority_queue<Ele>p1;
lowcost[1]=0;
Ele point,it;
point.len=0;
point.num=1;
p1.push(point);
while(!p1.empty())
{
// printf("11111\n");
it=p1.top();
p1.pop();
x=it.num;
if(Mark[x])
continue;
Mark[x]=true;
for(i=head[x];i!=-1;i=p[i].next)
if(!Mark[p[i].to]&&lowcost[p[i].to]>lowcost[x]+p[i].w)
{
lowcost[p[i].to]=lowcost[x]+p[i].w;
it.len=lowcost[p[i].to];
it.num=p[i].to;
p1.push(it);
}
}
}
int main()
{
int i;
int x,y,z;
while(scanf("%d%d",&n,&m),n&&m)
{
e=1;
memset(head,-1,sizeof(head));
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
Add(x,y,z);
Add(y,x,z);
}
Dij(1);
printf("%d\n",lowcost[n]);
}
return 0;
}
我做了 两天 ,总算做出来了,