题意:给出n个点,表示n座城市,现在想让每座城市都有电,所以需要再每座城市建发电站或者与相邻城市连接进行供电,在城市建发电站的花费是,城市i与城市j架接电线的花费是,请问如何设计才能使的花费最小。
思路:刚开始的想法特别混乱,觉得最暴力的解法就是枚举每一个作为建立发电站的点,然后跑最短路,取最小值,显然,如果这样跑的话,一定会超时。
那么还能怎么做??如何将这些零散的点整合到一起,从而降低时间复杂度?
证明:还没想通
收先建立一个超级终点,即虚点,然后将这个点与其他个点相连,虚点与其他各点有两条边,一条变得边权为c另一条的边权为,然后对建好的图跑kruskal得到最小生成树。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 5e6+5;
const int maxm = 2005;
struct edge{
int u, v;
LL cost;
};
bool cmp(const edge &e1, const edge &e2){
return e1.cost < e2.cost;
}
edge es[maxn];
struct Point{
LL x, y;
}P[maxm];
LL c[maxn];
LL k[maxn];
int cnt = 0;
int pre[maxn];
int n;
int f[maxn];
struct Node{
int u, v;
}ans[maxn];
int cnt1 = 0, cnt2 = 0;
void init(int n){
for(int i = 0; i <= n; i++) pre[i] = i;
}
int find(int x){
if(pre[x] == x) return x;
else return pre[x] = find(pre[x]);
}
bool mix(int x, int y){
int fx = find(x), fy = find(y);
if(fx != fy){
pre[fy] = fx;
return true;
}
return false;
}
LL kruskal(){
sort(es, es+cnt, cmp);
init(n);
LL res = 0;
int num = 0;
for(int i = 0; i < cnt && num != n; i++){
if(mix(es[i].u, es[i].v)){
res += es[i].cost;
if(es[i].u == 0){
f[cnt1++] = es[i].v;
}
else{
ans[cnt2].u = es[i].u;
ans[cnt2++].v = es[i].v;
}
num++;
}
}
return res;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%lld%lld", &P[i].x, &P[i].y);
for(int i = 1; i <= n; i++) scanf("%lld", &c[i]);
for(int i = 1; i <= n; i++) scanf("%lld", &k[i]);
for(int i = 1; i <= n; i++){
edge e; e.u = 0; e.v = i; e.cost = c[i];
es[cnt++] = e;
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
edge e;
LL len = abs(P[i].x - P[j].x) + abs(P[i].y - P[j].y);
e.u = i; e.v = j; e.cost = len * (k[i] + k[j]);
es[cnt++] = e;
}
}
LL res = kruskal();
printf("%lld\n", res);
sort(f, f+cnt1);
printf("%d\n", cnt1);
for(int i = 0; i < cnt1; i++){
printf("%d", f[i]);
if(i != cnt1) printf(" ");
}
printf("\n%d\n", cnt2);
for(int i = 0; i < cnt2; i++){
printf("%d %d\n", ans[i].u, ans[i].v);
}
return 0;
}