版权声明:希望能帮到弱校的ACMer成长,因为自己是弱校菜鸡~~~~ https://blog.csdn.net/Mr__Charles/article/details/82054783
HDU T2544 最短路
题目思路:
模板裸题......
Spfa写法:
#include<cstdio>
#include<queue>
#include<cstring>
#define maxm 10005
#define maxn 105
#define INF 0x3f3f3f3f
using namespace std;
struct Edge{
int to,cost,next;
}edge[maxm];
bool vis[maxn];
int dis[maxn],head[maxn],n,m,cnt;
void Init(){
memset(vis,false,sizeof(vis));
memset(head,-1,sizeof(head));
cnt = 0;
for(int i=1; i<=n; i++)
dis[i] = (i==1)? 0 : INF;
}
void add(int from,int to,int cost){
edge[cnt].to = to;
edge[cnt].cost = cost;
edge[cnt].next = head[from];
head[from] = cnt++;
}
void Spfa(int s){
int u;
queue<int> Q;
Q.push(s);
dis[s] = 0;
vis[s] = true;
while(!Q.empty()){
u = Q.front();
Q.pop();
vis[u] = false;
for(int i=head[u]; i!=-1; i=edge[i].next){
int v = edge[i].to;
int w = edge[i].cost;
if(dis[v] > dis[u] + w){
dis[v] = dis[u] + w;
if(!vis[v]){
vis[v] = true;
Q.push(v);
}
}
}
}
}
int main(){
int u,v,w;
while(scanf("%d%d",&n,&m),n+m){
Init();
for(int i = 0;i < m; i++){
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
Spfa(1);
printf("%d\n",dis[n]);
}
return 0;
}
Floyd写法
#include<cstdio>
#include<algorithm>
#define INF 0x3f3f3f3f
#define maxn 105
using namespace std;
int map[maxn][maxn],n,m;
void Init(){
for(int i = 0; i <= n; i++)
for(int j = 0; j <= n ;j++){
if(i == j) map[i][j] = 0; //floyd算法,要将对角线初始化为0!!!!
else map[i][j] = INF; //例:k==1,i=j==3;
}
}
void Floyd(){
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
map[i][j] = min(map[i][j],map[i][k]+map[k][j]);
}
int main(){
int a,b,c;
while(~scanf("%d%d",&n,&m),n+m)
{
Init();
for(int i = 0; i < m; i++){
scanf("%d%d%d",&a,&b,&c);
map[a][b] = map[b][a] = min(map[a][b],c);
}
Floyd();
printf("%d\n",map[1][n]);
}
return 0;
}