Kruskal 2015百度之星初赛2 HDOJ 5253 连接的管道
2024-09-08 12:14:52
/*
最小生成树(Kruskal):以权值为头,带入两个端点,自然的排序;感觉结构体的并查集很好看
注意:题目老头要的是两个农田的高度差,中文水平不好,题意理解成和平均值的高度差!
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
using namespace std; const int MAXN = 1e3 + ;
const int MAXM = 1e2 + ;
const int INF = 0x3f3f3f3f;
int n, m;
int a[MAXN][MAXN];
vector<pair<int, int> > G[MAXM];
struct UF
{
int rt[MAXN*MAXN];
void init(void) {memset (rt, -, sizeof (rt));} int Find(int x) {return (rt[x] == -) ? x : rt[x] = Find (rt[x]);} void Union(int x, int y)
{
x = Find (x); y = Find (y);
if (x > y) rt[y] = x;
else if (x < y) rt[x] = y;
} bool same(int x, int y) {return Find (x) == Find (y);}
}uf; int Kruskal(void)
{
uf.init ();
int ans = ;
for (int i=; i<=; ++i)
{
for (int j=; j<G[i].size (); ++j)
{
int u = G[i][j].first; int v = G[i][j].second;
if (!uf.same (u, v)) {uf.Union (u, v); ans += i;}
}
} return ans;
} int get_id(int i, int j) {return (i - ) * m + j;} int main(void) //2015百度之星初赛2 HDOJ 5253 连接的管道
{
int t, cas = ; scanf ("%d", &t);
while (t--)
{
scanf ("%d%d", &n, &m);
for (int i=; i<=; ++i) G[i].clear (); for (int i=; i<=n; ++i)
{
for (int j=; j<=m; ++j)
{
scanf ("%d", &a[i][j]);
if (i > ) {G[abs (a[i][j] - a[i-][j])].push_back (make_pair (get_id (i, j), get_id (i-, j)));}
if (j > ) {G[abs (a[i][j] - a[i][j-])].push_back (make_pair (get_id (i, j), get_id (i, j-)));}
}
} printf ("Case #%d:\n", ++cas);
printf ("%d\n", Kruskal ());
} return ;
} /*
2
4 3
9 12 4
7 8 56
32 32 43
21 12 12
2 3
34 56 56
12 23 4
*/
最新文章
- JS实现类似QQ好友头像hover时显示资料卡的效果
- VS2010+C#+EmguCV 配置详解
- win8.1安装Team Function Server 2013
- NPOI导出模板样式
- Android动画View Animation
- rest版的webservice
- Java学习之路(二)
- spring mvc 接受多对象的处置
- VLAN及Trunk实验
- 用require.js封装原生js轮播图
- 初读";Thinking in Java";读书笔记之第三章 --- 操作符
- Chart Parser 中 Earley&#39;s 算法的应用
- String Match
- MySQL高级知识(十二)——全局查询日志
- sql script: Graphs, Trees, Hierarchies and Recursive Queries
- AngularJS中使用$http对MongoLab数据表进行增删改查
- OO第一次课程总结分析
- AdMaster技术副总裁谈Hadoop、营销数据、Python和挖掘平台
- 怎样将 MySQL 迁移到 MariaDB 上
- php 自定义函数大全