其他分享
首页 > 其他分享> > F - Dragon Ball I

F - Dragon Ball I

作者:互联网

题目链接
还没懂,粘个代码

#include <bitsdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e3 + 10;
const ll inf = 0x3f3f3f3f3f3f3f3f;
ll dis[25][maxn];
ll vis[maxn];
ll n, m;
ll head[maxn], cnt, tot;
struct edge {
    ll to, w, nxt;
} e[maxn];

struct node {
    ll v, dis;
    bool operator<(const node &a) const { return dis > a.dis; }
} t, d;

void add(ll u, ll v, ll w) {
    e[cnt].to = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt++;
}
void dijstra(ll k) {
    memset(vis, 0, sizeof(vis));
    priority_queue<node> Q;
    t.v = k;
    t.dis = 0;
    Q.push(t);

    while (!Q.empty()) {
        if (vis[Q.top().v]) {
            Q.pop();
            continue;
        }
        t = Q.top();
        Q.pop();
        ll u = t.v;
        vis[u] = 1;
        dis[tot][u] = t.dis;
        for (ll i = head[u]; i != -1; i = e[i].nxt) {
            ll y = e[i].to, w = e[i].w;
            if (vis[y] == 0 && dis[tot][y] > dis[tot][u] + w) {
                dis[tot][y] = dis[tot][u] + w;
                d.v = y;
                d.dis = dis[tot][y];
                Q.push(d);
            }
        }
    }
    tot++;
}

signed main() {
    memset(head, -1, sizeof(head));
    memset(dis, 0x3f, sizeof(dis));
    cin >> n >> m;
    for (ll i = 0; i < m; i++) {
        ll u, v, w;
        cin >> u >> v >> w;
        add(u, v, w);
        add(v, u, w);
    }
    tot = 0;
    ll ans = inf;
    ll b[10];
    ll a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    dijstra(1);  //到自己一开始的最单路//dis[0][...]各点到1的距离
    for (ll i = 1; i <= 7; i++) {
        cin >> b[i];  //龙珠位置
        dijstra(b[i]);  //到龙珠的最短路//dis[1~7][...]各点到1~7个龙珠的最短路径
    }
    do {  //用全排列求路径
        ll now = dis[0][b[a[0]]];
        now += dis[a[0]][b[a[1]]];
        now += dis[a[1]][b[a[2]]];
        now += dis[a[2]][b[a[3]]];
        now += dis[a[3]][b[a[4]]];
        now += dis[a[4]][b[a[5]]];
        now += dis[a[5]][b[a[6]]];
        ans = min(ans, now);
    } while (next_permutation(a, a + 7));
    if (ans < inf)
        cout << ans << endl;
    else
        cout << "-1" << endl;
    return 0;
}

标签:head,Ball,ll,tot,Dragon,vis,now,dis
来源: https://blog.csdn.net/qq_47783181/article/details/113280469