CSU 1541 There is No Alternative (最小生成树+枚举)
2015-06-26 11:49
477 查看
题目链接:传送门
题意:
有n个点,m条边,要使n个点全部连起来且要花费最小,问有哪些边是必须要连的。
分析:
要使花费最小肯定是做最小生成树,但是题目要求哪些边是必须要用的。我们可以
这样思考,我们先求一次最小生成树,然后把这些用到的边统计起来,然后依次枚
举这n-1条边,使他们不能用,然后继续做最小生成树,如果最后求的值和第一次
不一样的话那么这条边是肯定要连的。
代码如下:
题意:
有n个点,m条边,要使n个点全部连起来且要花费最小,问有哪些边是必须要连的。
分析:
要使花费最小肯定是做最小生成树,但是题目要求哪些边是必须要用的。我们可以
这样思考,我们先求一次最小生成树,然后把这些用到的边统计起来,然后依次枚
举这n-1条边,使他们不能用,然后继续做最小生成树,如果最后求的值和第一次
不一样的话那么这条边是肯定要连的。
代码如下:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn = 50010; struct nod{ int x,y,val; bool operator < (const struct nod &tmp) const{ return this->val<tmp.val; } }edge[maxn]; int par[maxn/100],num[maxn/100]; int id[maxn/100]; int n,m; void init(){ for(int i=0;i<=n;i++) par[i]=i,num[i]=1; } int find_par(int x){ if(x!=par[x]) return par[x]=find_par(par[x]); return par[x]; } bool Union(int x,int y){ x=find_par(x); y=find_par(y); if(x!=y){ par[y]=x; num[x]+=num[y]; return true; } return false; } int ans ,cnt,sum1,sum2; void solve(){ sum1=sum2=0; for(int i=0;i<cnt;i++){ int tmp=0;init(); for(int j=0;j<m;j++){ if(j!=id[i]){ if(Union(edge[j].x,edge[j].y)) tmp+=edge[j].val; } } if(tmp!=ans) sum1++,sum2+=edge[id[i]].val; } printf("%d %d\n",sum1,sum2); } int main(){ while(~scanf("%d%d",&n,&m)){ init(); for(int i=0;i<m;i++){ scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].val); } sort(edge,edge+m); ans=0,cnt=0; memset(id,0,sizeof(id)); for(int i=0;i<m;i++){ if(Union(edge[i].x,edge[i].y)){ ans+=edge[i].val; id[cnt++]=i; } } solve(); } return 0; } /*** 4 4 1 2 3 1 3 5 2 3 3 2 4 3 4 4 1 2 3 1 3 1 2 3 3 2 4 3 3 3 1 2 1 2 3 1 1 3 1 ***/
相关文章推荐
- Android视图自定义View绘制流程完全解析,带你一步步深入了解View(二)
- 系统cell分割线长度
- poj2686
- ETL Pentaho Data Integration (Kettle) 插入/更新 问题 etl
- Java基础语法易犯错误(1)
- jsoncpp用法(判断void* pData是否为json格式的字符串)
- 关于json操作
- Linux下使用rsync最快速删除海量文件的方法
- HTML学习笔记
- 成为设计师的五项技能!最终章!
- SQL Case when 的使用方法
- CocoaPods 版本管理冲突 解决
- 递归与分治:归并排序法
- ORACLE同义词总结
- [原]深刻理解activity启动模式,彻底理解android的四种启动模式,尤其singleTask
- HTML 标签 <html>
- android xml布局文件中wrap_content的实际大小
- Java工程导入Eclipse
- 《计算机软件保护条例》
- hibernate 映射关系—关系映射(一对多)