HDU 1874 畅通工程续(最短路训练

时间:2023-12-25 09:57:19

因为数据比较小

所以flyod spfa dijkstra 多可以过

Floyd

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = ; int s[maxn][maxn];
int main (){
int n,m;
while(~scanf("%d %d",&n,&m) ){
for(int i=;i<n;i++){
for(int j=;j<n;j++){
if(i != j)
s[i][j] = INF;
else
s[i][j] = ;
}
}
for(int i=;i<m;i++){
int x,y,v; scanf("%d %d %d",&x,&y,&v);
s[x][y] = min(s[x][y],v);
s[y][x] = min(s[y][x],v);
}
for(int k=;k<n;k++)
for(int i=;i<n;i++)
for(int j=;j<n;j++)
s[i][j] = min(s[i][j],s[i][k]+s[k][j]);
int x,y;
scanf("%d %d",&x,&y);
if(s[x][y] == INF)
printf("-1\n");
else
printf("%d\n",s[x][y]);
}
}

spfa

// Spfa 算法

#include <bits/stdc++.h>
using namespace std;
const int maxn = ;
const int INF = 0x3f3f3f3f; vector <pair<int,int> >E[maxn];
int d[maxn],inq[maxn];//inq 代表的是是否in queue
int n,m;
void init(){
for(int i=;i<maxn;i++) d[i] = INF;
for(int i=;i<maxn;i++) inq[i] = ;
for(int i=;i<maxn;i++) E[i].clear();
}
int main()
{
while (~scanf("%d %d",&n,&m)){
init();
for(int i=;i<=m;i++){
int x,y,v;
scanf("%d %d %d",&x,&y,&v);
E[x].push_back(make_pair(y,v));
E[y].push_back(make_pair(x,v));
}
queue<int>Q;
int s,e;
scanf("%d %d",&s,&e);
d[s] = ;
inq[s] = ;//起点进队列
Q.push( s );
while (Q.size()){
int now = Q.front();
Q.pop(); inq[now] = ;//该点出队列
for(int i=;i < E[now].size();i++){
int y = E[now][i].first;
int v = E[now][i].second;
if(d[y] > d[now] + v )
{
d[y] = d[now] + v;
if( inq[y] )//如果在队列
continue;
inq[y] = ;
Q.push(y);
}
}
}
if(d[e] == INF)
printf("-1\n");
else
printf("%d\n",d[e]); }
return ;
}

dijkstra  //待测试

#include <bits/stdc++.h>
using namespace std;
const int maxn = ;
const int INF = 0x3f3f3f3f;
int n,m;
vector<pair<int,int> > E[maxn];
int d[maxn];
void init(){
for(int i=;i<maxn;i++)
E[i].clear() ,d[i] = INF;
}
int main()
{
while (~scanf("%d %d",&n,&m)){
init();
for(int i=;i<=m;i++){
int x,y,v;
scanf("%d%d%d",&x,&y,&v);
E[x].push_back(make_pair(y,v));
E[y].push_back(make_pair(x,v));
}
int s,e;//start end;
scanf("%d %d",&s,&e);
d[s] = ;
int v = -;
priority_queue<pair<int,int> > Q;
Q.push(make_pair(-d[s],s));
while ( !Q.empty() )
{
int now = Q.top().second;
if( now == e)//相等就可以直接跳出了
break;
Q.pop();
for(int i=;i < E[now].size();i++)
{
v = E[now][i].first;
if(d[v] > d[now] + E[now][i].second )
{
d[v] = d[now] + E[now][i].second;
Q.push(make_pair(-d[v],v));
}
} }
if(d[e] == INF)
printf("-1\n");
else
printf("%d\n",d[e]);
}
return ;
}