UVA10369 Arctic Network 最小生成樹 Prim算法

UVA10369 Arctic Network 最小生成樹 Prim


題面:

  • 題目的大概意思是,兩個地點如果各有一個satellite channel,那麼無論它們相隔多遠都能通信,而如果任何一個沒有satellite channel的話,就只能靠radio通信,而radio通信的成本與距離D是成正比的,現在希望讓所有地點都能直接或者間接通信,問最小的D是多少。

    參考博客:https://blog.yuki-nagato.com/


解題過程:

  • 因爲是稠密圖,肯定選用Prim算法。
  • 有多少個衛星,就可以去掉MST中的幾條邊。Prim的過程保證找到的n-1條邊是保證聯通的最小的邊的集合,每有一個衛星,就可以多一個聯通塊(MST的聯通塊爲1),就可以去掉一條邊。
  • 將MST中的邊排序,去掉前p長的邊即可。

AC代碼:


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
#define rep(i,l,p) for(int i=l;i<=p;i++)
#define fread() freopen("in.txt","r",stdin)
#define mp make_pair
typedef long long ll;
typedef pair<int ,int> P;
const int N = 505;
int n,p;
double a[N][N];
double x[N],y[N];
double d[N];
double ans;
bool v[N];
void prim(){
    rep(i,0,N-1) d[i] = 1e9;
    memset(v,0,sizeof v);
    d[1] = 0;
    for(int i=1;i<n;i++){
        int x = 0;
        for(int j=1;j<=n;j++){
            if(!v[j] && (x==0 || d[j] < d[x])) x = j;
        }
        v[x] = 1;
        for(int y=1;y<=n;y++){
            if(!v[y] && d[y] > a[x][y]){
                d[y] = a[x][y];
            }
        }
    }
}
double calc(int i,int j){
    return sqrt(1.0*(x[i]-x[j])*(x[i]-x[j]) + 1.0*(y[i]-y[j])*(y[i]-y[j]));
}
priority_queue<double,vector<double>,greater<double> > q;
int main(){
    ios::sync_with_stdio(false);
    int T;
    cin >> T;
    while(T--){
        cin >> p >> n;
        rep(i,0,N-1){
            rep(j,0,N-1){
                a[i][j] = 1e9;
            }
        }
        rep(i,1,n){
            cin >> x[i] >> y[i];
        }
        rep(i,1,n){
            rep(j,1,n){
               a[j][i] = a[i][j] = calc(i,j);
            //    cout << a[i][j] << endl;
            }
        }
        ans = 0.0;
        while(!q.empty()) q.pop();
        prim();
        // rep(i,1,n) printf("%.2lf\n", d[i]);

        rep(i,1,n){
            if(d[i] < 1e8) q.push(d[i]);
        }
        rep(i,1,n-p+1){
            ans = q.top();
            q.pop();
        }
        printf("%.2lf\n", ans);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章