Prim原始算法的可用性

T r u c k   H i s t o r y \color{red}Truck\ History Truck History

题意就是对于n个点,每个点到其他的有一定距离,找出最小生成树。
正常的Prim算法翻车惹,因为正常的复杂度为 2 m l o g m 2mlogm 2mlogm(优先队列实现),但是现在用到的一共有 n 2 n^2 n2条边,正常算法 2 n 2 l o g n 2 2n^2logn^2 2n2logn2 n n n 2000 2000 2000的,也就是 8 ∗ 1 0 7 8*10^7 8107,而实际上用邻接矩阵实现的,对于以前来说暴力的算法现在只有 2 n 2 2n^2 2n2的复杂度,反而更加优秀。
我们考虑,对于以前 n n n m m m较大,但是他们几乎相等或者差不了多少,复杂度只会有 2 n l o g n 2nlogn 2nlogn但是原始算法会是 n 2 n^2 n2。但是对于完全图或者近似完全图,这时候 m ≈ n 2 m≈n^2 mn2,那么优先队列优化反而多了个 10 10 10的复杂度。 B O O M ! BOOM! BOOM爆炸
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<cctype>
#include<string>
#include<cmath>
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define eps 1e-8
#define ll long long
using namespace std;

const int maxn = 2050;

int n;

bool vis[maxn];int minc[maxn];int ans=0;
char s[2020][9];
int p[2020][2020];

void prim(){
    memset(vis,0,sizeof(vis));
    vis[1]=true;
    int small,now;
    for(int i=1;i<=n;i++)minc[i]=p[1][i];
    for(int i=1;i<n;i++){
        small=0x3f3f3f3f;
        for(int j=1;j<=n;j++)if(minc[j]<small&&!vis[j]){small=minc[j];now=j;}
        ans+=small;vis[now]=true;
        for(int j=1;j<=n;j++)minc[j]=min(minc[j],p[now][j]);
    }
}

int cal(char a[],char b[]){
    int cnt=0;
    for(int i=0;i<7;i++){
        if(a[i]!=b[i])cnt++;
    }
    return cnt;
}

int main(){
    while(scanf("%d",&n)){
        ans=0;
        if(n==0)break;
        FOR(i,1,n)scanf("%s",s[i]);
        FOR(i,1,n)FOR(j,i+1,n){
            p[j][i]=p[i][j]=cal(s[i],s[j]);
        }
        prim();
        printf("The highest possible quality is 1/%d.\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值