題意:給出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;
}