求长度

牛客练习赛17 T5 题解链接

alt

法一

求出分别以s+1个点为源点的单源最短路,再全排列s个中间点的顺序,10!=362880010!=3628800,不会超时
next_permutation函数求全排列

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
const double eps = 1e-6;
const int N = 1e5 + 10, M = 2 * N;
int n, m, s;
int dist[11][N];
int h[N], ne[M], e[M], w[M], idx;
int mapp[11];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx++;
}

void spfa(int id)
{
    memset(st, 0, sizeof st);
    memset(dist[id], 0x3f, sizeof dist[id]);
    int u = mapp[id];
    queue<int> q;
    q.push(u);
    dist[id][u] = 0;
    st[u] = true;

    while (q.size())
    {
        int t = q.front();
        q.pop();
        st[t] = false;
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[id][j] > dist[id][t] + w[i])
            {
                dist[id][j] = dist[id][t] + w[i];
                if (!st[j])
                {
                    st[j] = true;
                    q.push(j);
                }
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        idx = 0;
        memset(h, -1, sizeof h);
        cin >> n >> m;
        while (m--)
        {
            int a, b, c;
            cin >> a >> b >> c;
            add(a, b, c), add(b, a, c);
        }
        cin >> s;
        for (int i = 1; i <= s; i++)
        {
            cin >> mapp[i];
        }
        for (int i = 0; i <= s; i++)
        {
            spfa(i);
        }
        vector<int> v(s + 1);
        for (int i = 1; i <= s; i++)
        {
            v[i] = i;
        }
        int ans = 0x3f3f3f3f;
        do
        {
            int d = dist[0][mapp[v[1]]] + dist[v[s]][0];
            for (int i = 1; i < s; i++)
            {
                int a = v[i], b = v[i + 1];
                d += dist[a][mapp[b]];
            }
            ans = min(ans, d);
        } while (next_permutation(v.begin() + 1, v.end()));
        cout << ans << '\n';
    }
    return 0;
}