最小生成树解题笔记(1)

*写在前面:在PAT上看到一道最小生成树的题目,榆树顺便复习了一下Kruskal和prim算法 *
By wck 2020/5/29

1. Prim算法解题思路:

Prim算法思路

  • prim算法底层数据结构使用临界矩阵存储,同时存储每个节点的是否访问(vis)和当前集合到各个点的最短路集合(dis),每次循环后都要对这两个数据结构进行维护

例题:HDU1863 链接:hdu1863

非常标准的最小生成树例题,没有任何其他要求,按部就班的写就好啦~~~

贴上AC代🐴:

#include<iostream>
#include<string>
#include<string.h>
#define INF 0xFFFFFFF
const int MAXN=105;
int m,n;
int road[MAXN][MAXN];
int vis[MAXN],dis[MAXN];
int solve(){
    for(int i=1;i<=m;i++){
        for(int j=0;j<=m;j++){
            road[i][j]=INF;
            
        }
    }
    for(int i=0;i<n;i++){
        int t1,t2,t3;
        std::cin>>t1>>t2>>t3;
        road[t2][t1] = road[t1][t2] = t3;
    }

    int res=0;
    memset(vis,0,sizeof(vis));
    int start=1;
    vis[start]=1;
    for(int i=1;i<=m;i++){
        dis[i]=road[start][i];
    }
    int numtime=m-1;
    while(numtime--){
        int next;
        int minr=INF;
        for(int i=1;i<=m;i++){ //遍历所有点,找到权最短路加入已遍历集合
            if(!vis[i] && dis[i]<minr){
                minr=dis[i];
                next=i;
            }
        }
        if(minr==INF){
            return -1;
        }
        vis[next]=1;res+=minr;
        for(int i=1;i<=m;i++){
            if(!vis[i] && road[next][i]<dis[i]){
                dis[i]=road[next][i];//更新最短路
            }
        }
    }
    return res;
}

using namespace std;
int main(){
    while(std::cin>>n>>m){
        if(n==0) return 0;
        int res=solve();
        if(res==-1){
            cout<<"?"<<endl;
        }
        else{
            cout<<res<<endl;
        }
    }
}

2.Kruskal 算法

在这里插入图片描述

  • Kruskal算法底层是并查集的结构实现的,已接连的节点存储在同一个father中,核心函数是Unionsetfindfather

例题:Hdu1879:hdu1879

思路:非常标准的最小生成树,稍微有所不同的是要注意在初始化时已经有合并好的集合,因此比较实用实用Kruskal算法。

照例贴上AC代🐴啦啦啦~~

#include<iostream>
#include<algorithm>
#include<set>

const int MAXN=105;

struct road
{
public:
    int start,end,cost;
    /* data */
};


int father[MAXN];
road s_data[MAXN*MAXN];
int n;


int findfather(int i){
    if(father[i]==i) return i;
    else return father[father[i]];
}

int unionset(int i1,int i2){
    int f1=findfather(i1);
    int f2=findfather(i2);
    if(f1==f2) return 0;
    else{
        if(f1<f2){
            father[i2]=f1;
        }
        else{
            father[i1]=f2;
        }
    }
    return 1;
}
int getsum(){
    int res;
    for(int i=0;i<n;i++){
        res+=findfather(i);
    }
    return res;
}
bool roadcmp(road t1,road t2){
    return t1.cost < t2.cost;
}
void solve(){
    for(int i=0;i<n;i++){
        father[i]=i;
    }
    int roadn=n*(n-1)/2;
    int res=0;
    int t=0;
    for(int i=0;i<roadn;i++){
       road tmpr;
       int state;
       scanf("%d%d%d%d",&tmpr.start,&tmpr.end,&tmpr.cost,&state);
        if(state==1){
            unionset(tmpr.start,tmpr.end);//道路连通
        }
        else if(state==0){
            s_data[t++]=tmpr;
        }
    }
    std::sort(s_data,s_data+n,roadcmp);
    for(int i=0;i<t;i++){
        if(unionset(s_data[i].start,s_data[i].end)){
            res+=s_data[i].cost;
        }
        if(getsum()==0){
            break;
        }
    }
    std::cout<<res<<std::endl;
    return;
}

int main(){
    while(std::cin>>n){
        if(n==0)
        break;
        solve();
    }
}

3. 应用

例题:pat1001 Battle Over Cities - Hard Version

pat1001链接

描述:

It is vitally important to have all the cities connected by highways in a war. If a city is conquered by the enemy, all the highways from/toward that city will be closed. To keep the rest of the cities connected, we must repair some highways with the minimum cost. On the other hand, if losing a city will cost us too much to rebuild the connection, we must pay more attention to that city.

Given the map of cities which have all the destroyed and remaining highways marked, you are supposed to point out the city to which we must pay the most attention.
Input Specification:

Each input file contains one test case. Each case starts with a line containing 2 numbers N (≤500), and M, which are the total number of cities, and the number of highways, respectively. Then M lines follow, each describes a highway by 4 integers: City1 City2 Cost Status where City1 and City2 are the numbers of the cities the highway connects (the cities are numbered from 1 to N), Cost is the effort taken to repair that highway if necessary, and Status is either 0, meaning that highway is destroyed, or 1, meaning that highway is in use.

Note: It is guaranteed that the whole country was connected before the war.
Output Specification:

Input

For each test case, just print in a line the city we must protest the most, that is, it will take us the maximum effort to rebuild the connection if that city is conquered by the enemy.

Output

In case there is more than one city to be printed, output them in increasing order of the city numbers, separated by one space, but no extra space at the end of the line. In case there is no need to repair any highway at all, simply output 0.

思路:

这题有一些特殊的是,需要求出那个点去除后的最小生成树最大;我没有想出很快的数据结构,我采用的是对所有点删除后,计算其剩下节点的最小生成树,😄很幸运的是并没有超时;
这个操作只需要通过将该节点的vis设置为1即可实现非常简单而且不会产生冲突
注意pat蛋疼的输出格式要求!!!因为这个wa了好几次😗

贴上AC代🐴

/**
 * Write by wck 2020/5/29 
 * 最小生成树 prim算法
*/

#include<iostream>
#include<algorithm>
#include<fstream>
#include<string>
#include <stdio.h>
#include <string.h>
#include<sstream>
using namespace std;
#define INF 0xFFFFFFF
const int MAXN=505;
int road[MAXN][MAXN];//邻接矩阵存储各路长度
int cost[MAXN];//存取每个村庄移除代价 
int vis[MAXN];
int n;


void prim(int v)
{   //prim算法求去除村庄v之后的最小生成树
    int numleft=n-2;//除了村庄和起点仍有n-2个村庄 
    int start= v==n-1? 0:v+1;  //定义开始遍历起点
    memset(vis,0,MAXN);
    vis[v]=vis[start]=1;
    int next=0;
    int dis[MAXN];      //记录连通部分到各点最短距离
    for(int i=0;i<n;i++){
        dis[i]=road[start][i];
    }
    while(numleft--){
        int minr=INF;
        for(int i=0;i<n;i++){
            if( !vis[i] && dis[i]<minr){
                minr=dis[i];
                next=i;
            }
        }
        if(minr==INF){
            cost[v]=INF;
            break;//无法连通
        }
        vis[next]=1;cost[v]+=minr; //更新最短距离矩阵
        for(int i=0;i<n;i++){
            if(!vis[i] && road[next][i] < dis[i]){
                dis[i]=road[next][i];
            }
        }//判断加入next点后是否需要更新最短距离矩阵
    }
}

int main(){
    int m;
    string str;
    // ifstream cin("input2.txt");
    cin>>n>>m;    
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
             road[i][j]=INF;
        }
    }
        while(m--){
            int t1,t2,t3,t4;
            cin>>t1>>t2>>t3>>t4;
            t1--;t2--;
            if(t4==1){//道路连通
                road[t1][t2]=road[t2][t1]=0;
            }
            else if(t4==0){
                road[t1][t2]=road[t2][t1]=t3;
            }
        }
        memset(cost,INF,n);
        int maxcost=0;
        for(int i=0;i<n;i++){
            prim(i);
            if(cost[i]>maxcost){       
                maxcost=cost[i];
            }
        }
        if(maxcost==0){
            cout<<"0";
        }
        else{
            bool flag=1;
            for(int i=0;i<n;i++){
                if(cost[i]==maxcost){
                    if(flag==1){
                        cout<<i+1;//首位输出不带空格
                    flag=0;
                    }
                    else  cout<<" "<<i+1;
                }
            }
    }
    // system("pause");
    return 0;
}

最后祝大家解题愉快~~😆😆😆

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值