暢通工程續 HDU
阿新 • • 發佈:2018-12-22
#include<bits/stdc++.h> #include<iostream> #include<vector> #include<cstring> #include<algorithm> #define maxn 205 using namespace std; vector<pair<int, int> >E[maxn]; int n, m; int d[maxn], inq[maxn]; void init(){ for(int i = 0; i < maxn; i++) E[i].clear(); for(int i = 0; i < maxn; i++) inq[i] = 0; for(int i = 0; i < maxn; i++) d[i] = 1e7; } int main(){ while(cin >> n >> m){ init(); /*for(int i = 0; i < n; i++){ printf("inq[%d] = %d \n", i, inq[i]); } for(int i = 0; i < n; i++){ printf("d[%d] = %d \n", i, d[i]); }*/ //列印初始化 for(int i = 0; i < m; i++){ int x, y, z;scanf("%d%d%d", &x, &y, &z); E[x].push_back(make_pair(y, z)); E[y].push_back(make_pair(x, z));//雙向表 } /*for(int x = 0; x < m; x++){ for(int i = 0; i < E[x].size(); i++) printf("E[%d][%d] = %d %d\n", x, i, E[x][i].first, E[x][i].second); }*/ //每個點都有邊的話可以這樣輸出 int s, t; scanf("%d%d", &s, &t); queue<int> Q; Q.push(s), d[s] = 0; inq[s] = 1; while(!Q.empty()){ int now = Q.front(); Q.pop(), inq[now] = 0; for(int i = 0; i < E[now].size(); i++){ int v = E[now][i].first; if(d[v] > d[now] + E[now][i].second){ d[v] = d[now] + E[now][i].second; if(inq[v] == 1) continue; inq[v] = 1; Q.push(v); } } } if(d[t] == 1e7){ printf("-1\n"); }else{ printf("%d\n", d[t]); } } return 0; }