题意:给出一堆双向路,求从N点到1点的最短路径,最裸的最短路径,建完边之后直接跑dij或者spfa就行
dij:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
typedef pair<int,int> pii;
const int INF=0x3f3f3f3f; int head[],dist[],point[],val[],next[],size; void add(int a,int b,int v){
int i;
for(i=head[a];~i;i=next[i]){
if(point[i]==b){
if(val[i]>v)val[i]=v;
return;
}
}
point[size]=b;
val[size]=v;
next[size]=head[a];
head[a]=size++;
} struct cmp{
bool operator()(pii a,pii b){
return a.first>b.first;
}
}; void dij(int s){
int i;
priority_queue<pii,vector<pii>,cmp>q;
q.push(make_pair(,s));
memset(dist,-,sizeof(dist));
dist[s]=;
while(!q.empty()){
pii p=q.top();
q.pop();
if(p.first>dist[p.second])continue;
for(i=head[p.second];~i;i=next[i]){
int j=point[i];
if(dist[j]==-||dist[j]>p.first+val[i]){
dist[j]=p.first+val[i];
q.push(make_pair(dist[j],j));
}
}
}
printf("%d\n",dist[]);
} int main(){
int t,n;
while(scanf("%d%d",&t,&n)!=EOF){
int i,j;
size=;
memset(head,-,sizeof(head));
for(i=;i<=t;i++){
int a,b,v;
scanf("%d%d%d",&a,&b,&v);
add(a,b,v);
add(b,a,v);
}
dij(n);
}
return ;
}
dij
spfa:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std; int head[],dist[],next[],point[],val[],size;
bool vis[]; void add(int a,int b,int v){
int i;
for(i=head[a];~i;i=next[i]){
if(point[i]==b){
if(val[i]>v)val[i]=v;
return;
}
}
point[size]=b;
val[size]=v;
next[size]=head[a];
head[a]=size++;
} void spfa(int s,int p){
memset(vis,,sizeof(vis));
memset(dist,-,sizeof(dist));
queue<int>q;
vis[s]=;
dist[s]=;
q.push(s);
while(!q.empty()){
int i,t=q.front();
vis[t]=;
q.pop();
for(i=head[t];~i;i=next[i]){
int j=point[i];
if(dist[j]==-||dist[j]>dist[t]+val[i]){
dist[j]=dist[t]+val[i];
if(!vis[j]){
q.push(j);
vis[j]=;
}
}
}
}
printf("%d\n",dist[p]);
} int main(){
int t,n;
while(scanf("%d%d",&t,&n)!=EOF){
int i,j;
memset(head,-,sizeof(head));
size=;
for(i=;i<=t;i++){
int a,b,v;
scanf("%d%d%d",&a,&b,&v);
add(a,b,v);
add(b,a,v);
}
spfa(n,);
}
return ;
}
spfa