1032 Fighting the Monster

裸体最小生成树

背个模板就可以了 没有难度

  1. 理解什么是最小生成树
  2. 理解题目要求
#include 
#include 
using namespace std;
const int N = 10010;
const int M = 10010;
int n,m;
struct Edge{
    int u,v,p,w,id;
    bool operator <(const Edge& e){
        if(p == e.p){
            return w > e.w;
        }else{
            return p < e.p;
        }
    }
}edges[N];
int fa[N];
int find(int x){
    if(x != fa[x]){
        fa[x] = find(fa[x]);
    }
    return fa[x];
}
void merge(int x,int y){
    fa[find(x)] = find(y);
}
vector<int> monsters;
int main(){
    cin>>n>>m;
    for(int i = 0;i<m;i++){
        int u,v,p,w;
        cin>>u>>v>>p>>w;
        edges[i]  = {u,v,p,w,i+1};
    }
    for(int i = 0;i<n;i++){
        fa[i] = i;
    }
    sort(edges,edges+m);
    int sum = 0;
    int maxWeapon = -1e8;
    int sumofw = 0;
    int cnt = 0;
    for(int i  =0;i<m;i++){
        int u,v,p,w;
        u = edges[i].u;
        v = edges[i].v;
        p = edges[i].p;
        w = edges[i].w;
        if(find(u) == find(v)){
            continue;
        }
        sum += p;
        maxWeapon = max(maxWeapon,w);
        sumofw += w;
        cnt++;
        merge(u,v);
        monsters.push_back(edges[i].id);
        if(cnt  == n-1){
            break;
        }
    }    
    sort(monsters.begin(),monsters.end());
    cout<<sum<<" ";
    cout<<sumofw<<endl;
    for(int i = 0;i<monsters.size();i++){
        if(i != monsters.size()-1){
        cout<<monsters[i]<<" ";
        }else{
            cout<<monsters[i];
        }
    }
    
}

你可能感兴趣的:(网络编程,算法,算法,c++,开发语言)