ZOJ 3204 Connect them最小生成树
来源:互联网 发布:js中createelement 编辑:程序博客网 时间:2024/06/05 22:59
ZOJ 3204 Connect them
最小生成树,输出字典序最小的解。
先排序,用kruscal算法,输出的时候按照字典序排序。
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int N=100+5;struct Edge{ int from, to; int w;}edge[N*N];Edge ans[N*N];int father[N];int tol, cnt;void add_edge(int u, int v, int w){ edge[tol].from=u; edge[tol].to=v; edge[tol].w=w; tol++;}bool cmp1(Edge a, Edge b){ if(a.w!=b.w) return a.w < b.w; if(a.from != b.from) return a.from < b.from; return a.to < b.to;}bool cmp2(Edge a, Edge b){ if(a.from != b.from) return a.from < b.from; return a.to < b.to;}int find(int x){ if(father[x] == -1) return x; return father[x]=find(father[x]);}void kruscal(){ memset(father,-1,sizeof(father)); cnt=0;//加入最小生成树的边数 for(int k=0;k<tol;k++){ int u=edge[k].from; int v=edge[k].to; u=find(u); v=find(v); if(u!=v){ ans[cnt++]=edge[k]; father[u]=v; } }}void init(){ tol=0; cnt=0; memset(edge,0,sizeof(edge));}int main(){ int T, n; cin >> T; while(T--){ init(); cin >> n; int w; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ cin >> w; if(j<=i || w==0) continue; add_edge(i,j,w); } sort(edge,edge+tol,cmp1); kruscal(); if(cnt!=n-1) { printf("-1\n"); continue; } sort(ans,ans+cnt,cmp2); for(int i=0;i<cnt-1;i++) printf("%d %d ",ans[i].from, ans[i].to); printf("%d %d\n",ans[cnt-1].from,ans[cnt-1].to); } return 0;}
阅读全文
1 0
- zoj 3204 Connect them//最小生成树
- Connect them - ZOJ 3204 最小生成树
- 【最小生成树】 ZOJ 3204 Connect them
- ZOJ 3204Connect them(最小生成树)
- ZOJ 3204 Connect them最小生成树
- ZOJ 3204 Connect them 最小生成树+字典序最小
- ZOJ-3204 Connect them(最小生成树)
- ZOJ 3204 Connect them(最小生成树:kruscal算法)
- zoj 3204 Connect them 最小生成树 打印路径
- ZOJ 3204 Connect them(最小生成树之Krusal 输出字典序最小的)
- zoj 3204 2966 Connect them|建设电力系统(最小生成树)
- ZOJ-3204-Connect them【6th浙江省赛】【最小生成树】
- ZOJ 3204 Connect them 【最小生成树+输出选取的边】
- zoj3204 Connect them 最小生成树 MST
- zoj3204 connect them 最小生成树 暴力
- ZOJ - 3204 Connect them
- ZOJ 3204 Connect them
- ZOJ 3204 Connect them
- 网址解析
- 王者系列之Mybatis入门配置(maven版本)
- 在规则下编程
- MySQL Navicat Premium使用技巧
- Sagheer and Nubian Market
- ZOJ 3204 Connect them最小生成树
- Hadoop学习(1)——MapReduce的原理和操作
- 目前机器视觉的大牛
- 数组、链表、栈、队列和STL简介+对比
- Android Activity对象创建流程
- Maven 项目管理 —— 安装与配置
- RabbitMQ安装与环境变量配置
- qsort 结构体二级排序
- 自研视频直播技术点分析及使用LFLiveKit,ijkplayer