F - Dragon Ball I

F - Dragon Ball I(多次最短路记录)

题目链接
经过自己很多天的思考,终于是弄明白了这个题。首先是用dis数组存好各点到1的距离,然后又存了各点到每个龙珠的距离(这里有一个巧妙的办法,即使是相同地点的龙珠也要再存一个新的,因为后面用了全排列枚举,所以可以这么做),存完之后,就全排列枚举出一个最小的路来。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5 + 10;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll dis[25][N];
bool st[N];
int n, m, idx;
int e[N], ne[N], h[N], w[N];
int tot;
typedef pair<int, int> PII;
void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}

void dijkstra(int x)
{
    memset(st, 0, sizeof st);
    dis[tot][x] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({x, dis[tot][x]});
    while(heap.size())
    {
        auto t = heap.top();
        heap.pop();
        int ver = t.first;
        ll distance = t.second;
        for(int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(dis[tot][j] > distance + w[i])
            {
                dis[tot][j] = distance + w[i];
                heap.push({j, dis[tot][j]});
            }
        }
    }
    tot ++;
}


int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    memset(dis, 0x3f, sizeof dis);
    for(int i = 0; i < m; i ++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    ll ans = INF;
    ll b[10];
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    dijkstra(1);
    for(int i = 1; i <= 7; i ++)
    {
        cin >> b[i];
        dijkstra(b[i]);
    }
    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;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页