Codeforces Round #597 (Div. 2) D. Shichikuji and Power Grid 最小生成树

题目:http://codeforces.com/contest/1245/problem/D

题意: 有n个城市每个城市之间都有路,两城市连接电线的花费为(abs(x-x)+abs(y-y))*(k+k), 建立发电场的费用为ci

问使所有城市都有电的最小代价。

思路:明显的最小生成树,设置一个0号点连接每个点的代价为建立发电场的代价,然后构建完全图求最小生成树,与0号点连接的点表示建立发电场。即可。

ac代码:

#include <cstdio>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

const int mx = 2e3+100;
typedef long long ll;
const ll mo = 1e9+7;
const ll inf = 0x3f3f3f3f;
struct node {
    ll x, y, c, k;
}N[mx];
int tot, co[mx][mx];
vector<ll>ve[mx], cs;
struct edge {
    ll x, y, e;
    edge() {}
    edge(ll xx, ll yy, ll ee):x(xx),y(yy),e(ee) {}
    bool operator<(const edge &t) const {
        return e<t.e;
    }
}E[mx*mx];
ll dis(ll x, ll y) {
    return (abs(N[x].x-N[y].x)+abs(N[x].y-N[y].y))*(N[x].k+N[y].k);
}
ll n;
int fa[mx];

void init() {
    for (int i = 1; i <= n; ++i) fa[i] = i;
}

ll Find(ll x) {
    return x == fa[x] ? x : fa[x] = Find(fa[x]);
}

ll sum;

void solve() {
    init();
    ll ts = 0;
    sort(E, E+tot);
    for (int i = 0; i < tot; ++i) {
        ll fx = Find(E[i].x), fy = Find(E[i].y);
        if (fx == fy) continue;
        fa[fx] = fy;
        if (E[i].x == 0) cs.push_back(E[i].y);
        else E[ts++] = E[i];
        sum += E[i].e;
    }
    printf("%lld\n", sum);
    cout << cs.size() << endl << cs[0];
    for (int i = 1; i < cs.size(); ++i){
        ll v = cs[i];
        printf(" %lld", v);
    }
    puts("");
    printf("%lld\n", ts);
    for (int i = 0; i < ts; ++i)
        printf("%lld %lld\n", E[i].x, E[i].y);
}

int main () {
    scanf("%lld", &n);
    for (ll i = 1; i <= n; ++i)
        scanf("%lld%lld", &N[i].x, &N[i].y);
    for (ll i = 1; i <= n; ++i) {
        scanf("%lld", &N[i].c);
        E[tot++] = edge(0, i, N[i].c);
    }
    for (ll i = 1; i <= n; ++i) scanf("%lld", &N[i].k);
    for (ll i = 1; i <= n; ++i)
        for (ll j = i+1; j <= n; ++j)
            E[tot++] = edge(i, j, dis(i, j)),
            co[i][j] = dis(i, j),
            co[j][i] = dis(i, j);


    solve();
    return 0;
}
发布了74 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ClonH/article/details/102897826