许诺 • 23天前
#include <bits/stdc++.h>
using namespace std;
const int INF = INT_MAX / 2;
int main() {
int n, m;
while(cin >> n >> m)
{
vector<vector<pair<int, int>>> adj(n);
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
a--; b--;
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
int pow3[11] = {1};
for (int i = 1; i <= n; ++i) {
pow3[i] = pow3[i - 1] * 3;
}
int total_states = pow3[n];
vector<vector<int>> dp(total_states, vector<int>(n, INF));
queue<pair<int, int>> q;
for (int u = 0; u < n; ++u) {
int s = pow3[u];
dp[s][u] = 0;
q.emplace(s, u);
}
while (!q.empty()) {
auto [s, u] = q.front();
q.pop();
for (auto [v, c] : adj[u]) {
int k = (s / pow3[v]) % 3;
if (k >= 2) continue;
int new_s = s + pow3[v];
int new_cost = dp[s][u] + c;
if (new_cost < dp[new_s][v]) {
dp[new_s][v] = new_cost;
q.emplace(new_s, v);
}
}
}
int min_cost = INF;
for (int s = 0; s < total_states; ++s) {
bool valid = true;
for (int i = 0; i < n; ++i) {
if ((s / pow3[i]) % 3 == 0) {
valid = false;
break;
}
}
if (valid) {
for (int u = 0; u < n; ++u) {
if (dp[s][u] < min_cost) {
min_cost = dp[s][u];
}
}
}
}
if (min_cost == INF) {
cout << -1 << endl;
} else {
cout << min_cost << endl;
}
}
return 0;
}
评论:
请先登录,才能进行评论