ZOJ - 1586 QS Network

題目連接:

  https://zoj.pintia.cn/problem-sets/91827364500/problems/91827365085ios

思路:

   大體也是一個模板題,主要的區別就是邊的權值要加上兩點的價格,Kruskal交了好幾發都不給過,看題解換成prim就過了,prim()yyds。

代碼:

#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iomanip>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)

using namespace std;

typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 1010;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n, m;
int a[N][N];
int price[N];

bool vis[N];
int dis[N];
ll prim()
{
    memset(dis, INF, sizeof dis), memset(vis, 0, sizeof vis);
    ll res = 0;
    for (int i = 1; i <= n; i++)
    {
        int t = -1;
        for (int j = 1; j <= n; j++)
        {
            if (vis[j])
                continue;
            if (t == -1 || dis[j] < dis[t])
                t = j;
        }
        vis[t] = 1;
        if (t != 1)
            res += dis[t];
        for (int j = 1; j <= n; j++)
            dis[j] = min(dis[j], a[t][j]);
    }
    return res;
}

int main()
{
    fastio;
    int T;
    cin >> T;
    while (T--)
    {
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> price[i];
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
            {
                cin >> a[i][j];
                a[i][j] += price[i] + price[j];
            }
        cout << prim() << endl;
    }
    return 0;
}
相關文章
相關標籤/搜索