zoukankan      html  css  js  c++  java
  • BZOJ 2753: [SCOI2012]滑雪与时间胶囊(最小生成树)

    解题思路

      一道很巧妙的题。首先看题目很可能想到最小树形图,但最小树形图是(O(nm))的。所以要注意一些特殊的性质。首先第一问可以直接(dfs)一遍求解,对于第二问可以把所有能到的点按高度分层,发现对于每一层只能由同层或上层转移来,那么就可以利用这个性质用最小生成树来做,排序的时候第一关键字为终点的高度,第二关键字为权值,然后跑最小生成树即可。

    代码

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<algorithm>
    
    using namespace std;
    const int N=1000005;
    typedef long long LL;
    
    inline int rd(){
    	int x=0,f=1;char ch=getchar();
    	while(!isdigit(ch)) f=ch=='-'?0:1,ch=getchar();
    	while(isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
    	return f?x:-x;
    }
    
    int n,m,h[N],head[N],cnt;
    int to[N<<1],nxt[N<<1],sum,fa[N];
    LL ans;
    bool vis[N];
    
    inline void add(int bg,int ed){
    	to[++cnt]=ed,nxt[cnt]=head[bg],head[bg]=cnt;
    }
    
    struct Edge{
    	int u,v,w;
    	friend bool operator<(const Edge A,const Edge B){
    		if(h[A.v]==h[B.v]) return A.w<B.w;
    		return h[A.v]>h[B.v];
    	}
    }edge[N];
    
    void dfs(int x){
    	vis[x]=1;sum++;
    	for(int i=head[x];i;i=nxt[i]){
    		if(vis[to[i]]) continue;
    		dfs(to[i]);
    	}
    }
    
    int get(int x){
    	if(fa[x]==x) return x;
    	return fa[x]=get(fa[x]);
    }
    
    int main(){
    	n=rd(),m=rd();
    	for(int i=1;i<=n;i++) h[i]=rd(),fa[i]=i;
    	for(int i=1;i<=m;i++){
    		edge[i].u=rd(),edge[i].v=rd(),edge[i].w=rd();
    		if(h[edge[i].u]<h[edge[i].v]) swap(edge[i].u,edge[i].v);
    		if(h[edge[i].u]==h[edge[i].v]) add(edge[i].u,edge[i].v),add(edge[i].v,edge[i].u);
    		else add(edge[i].u,edge[i].v);
    	}
    	dfs(1);printf("%d ",sum);
    	sort(edge+1,edge+1+m);int tot=0,x,y;
    	for(int i=1;i<=m;i++){
    		x=edge[i].u,y=edge[i].v;
    		if(!vis[x] || !vis[y]) continue;
    		x=get(x);y=get(y);
    		if(x!=y) fa[x]=y,ans+=edge[i].w,tot++;
    		if(tot==sum-1) break;
    	}
    	printf("%lld
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    iconv 文件编码转换
    source insight 中文注释为乱码解决
    c: c代码书写规范
    Ubuntu: 搭建tftp,nfs服务器
    Linux: 信息查看
    liteos时间管理(九)
    最大连续子数列和
    递归为什么那么慢?递归的改进算法
    liteos信号量(八)
    liteos互斥锁(七)
  • 原文地址:https://www.cnblogs.com/sdfzsyq/p/10274365.html
Copyright © 2011-2022 走看看