Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ワーシャルフロイド法。全点対最短距離を求める。O(|V|^3)なので計算量に余裕があるときに使える。マクロ等は https://gist.github.com/aximov/ff8a13ad8aa6c338ec4f88d8970cc1ad
const int MAX_V = (int)200;
int d[MAX_V][MAX_V]; // d[u][v]は辺(u,v)のコスト。0-origin. 初期化忘れずに
int V;
void warshall_floyd() {
REP(k, V)
REP(i, V)
REP(j, V) d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
signed main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
// 使用例 https://atcoder.jp/contests/abc073/tasks/abc073_d
int M,R;
cin >> V >> M >> R;
vector<int> r(R);
REP(i,R) {
cin >> r[i];
--r[i];
}
sort(ALL(r));
// コスト情報初期化
REP(i, V) {
fill(d[i], d[i] + V, LINF);
d[i][i] = 0;
}
// コスト入力
REP(i,M) {
int a,b,c;
cin >> a >> b >> c;
--a; --b;
// 有向・無向の区別注意
d[a][b] = c;
d[b][a] = c;
}
warshall_floyd();
int ans = LINF;
do {
int tmp = 0;
REP(i,R-1) tmp += d[r[i]][r[i+1]];
ans = min(ans,tmp);
} while (next_permutation(ALL(r)));
cout << ans << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.