HDU 1874 畅通工程续(最短路训练
因为数据比较小
所以flyod spfa dijkstra 多可以过
Floyd
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 210; int s[maxn][maxn]; int main (){ int n,m; while(~scanf("%d %d",&n,&m) ){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i != j) s[i][j] = INF; else s[i][j] = 0; } } for(int i=0;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=0;k<n;k++) for(int i=0;i<n;i++) for(int j=0;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 = 210; 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=0;i<maxn;i++) d[i] = INF; for(int i=0;i<maxn;i++) inq[i] = 0; for(int i=0;i<maxn;i++) E[i].clear(); } int main() { while (~scanf("%d %d",&n,&m)){ init(); for(int i=1;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] = 0; inq[s] = 1;//起点进队列 Q.push( s ); while (Q.size()){ int now = Q.front(); Q.pop(); inq[now] = 0;//该点出队列 for(int i=0;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] = 1; Q.push(y); } } } if(d[e] == INF) printf("-1\n"); else printf("%d\n",d[e]); } return 0; }
dijkstra //待测试
#include <bits/stdc++.h> using namespace std; const int maxn = 210; const int INF = 0x3f3f3f3f; int n,m; vector<pair<int,int> > E[maxn]; int d[maxn]; void init(){ for(int i=0;i<maxn;i++) E[i].clear() ,d[i] = INF; } int main() { while (~scanf("%d %d",&n,&m)){ init(); for(int i=1;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] = 0; int v = -1; 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=0;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 0; }