比赛 2025暑期集训第5场图论专场 评测结果 AAAAATTMTTTTT
题目名称 Telephone 最终得分 38
用户昵称 健康铀 运行时间 14.644 s
代码语言 C++ 内存使用 83.09 MiB
提交时间 2025-07-09 11:13:31
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;

int main() {
    freopen("telephone.in", "r", stdin);
    freopen("telephone.out", "w", stdout);

    int n, k;
    cin >> n >> k;
    vector<int> b(n + 1);
    for (int i = 1; i <= n; i++) {
        cin >> b[i];
    }

    vector<string> mat(k);
    for (int i = 0; i < k; i++) {
        cin >> mat[i];
    }

    vector<vector<pair<int, int>>> g(n + 1);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == j) continue;
            if (mat[b[i] - 1][b[j] - 1] == '1') {
                int c = abs(i - j);
                g[i].push_back({j, c});
            }
        }
    }

    vector<int> d(n + 1, INF);
    d[1] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, 1});

    while (!pq.empty()) {
        int cd = pq.top().first;
        int u = pq.top().second;
        pq.pop();
        if (cd != d[u]) continue;
        for (auto &e : g[u]) {
            int v = e.first;
            int w = e.second;
            if (d[u] + w < d[v]) {
                d[v] = d[u] + w;
                pq.push({d[v], v});
            }
        }
    }

    if (d[n] == INF) {
        cout << -1 << endl;
    } else {
        cout << d[n] << endl;
    }

    return 0;
}