hdu 1189 并查集
Farm Irrigation
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4802 Accepted Submission(s): 2073
Figure 1
Benny has a map of his farm, which is an array of marks denoting the distribution of water pipes over the whole farm. For example, if he has a map
ADC
FJK
IHE
then the water pipes are distributed like
Figure 2
Several wellsprings are found in the center of some squares, so water can flow along the pipes from one square to another. If water flow crosses one square, the whole farm land in this square is irrigated and will have a good harvest in autumn.
Now Benny wants to know at least how many wellsprings should be found to have the whole farm land irrigated. Can you help him?
Note: In the above example, at least 3 wellsprings are needed, as those red points in Figure 2 show.
#include<iostream>
#include<cstdio>
#include<cstring>
#define N 55
using namespace std; int n,m,f[N*N];
int map[][];
int dir[][]={{,-},{-,},{,},{,}}; int farm[][]={
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,},
{,,,}
}; void init(){ for(int i=; i<N*N; ++i)f[i]=i;} int findset(int x){ return f[x]!=x?f[x]=findset(f[x]):f[x];} void merge(int x,int y)
{
int a=findset(x), b=findset(y);
if(a==b)return ;
if(a<b) f[a]=b;
else f[b]=a;
} int main()
{
int i,j,k,dx,dy;
char ch;
while(scanf("%d%d%",&n,&m))
{
if(n==- && m==-) break;
for(i=; i<n; ++i)
{
for(j=; j<m; ++j)
{
scanf("%c",&ch);
map[i][j]=ch-'A';
}
getchar();
}
init();
for(i=; i<n; ++i)
{
for(j=; j<m; ++j)
{
for(k=; k<; ++k)
{
dx=i+dir[k][],dy=j+dir[k][];
if(dx<||dx>=n||dy<||dy>=m)continue;
if(k==)// 左
{
if(farm[map[dx][dy]][]&&farm[map[i][j]][]){
merge(dx*m+dy, i*m+j);
}
}
else if(k==)// 上
{
if(farm[map[dx][dy]][]&&farm[map[i][j]][]){
merge(dx*m+dy, i*m+j);
}
}
else if(k==)// 右
{
if(farm[map[dx][dy]][]&&farm[map[i][j]][]){
merge(dx*m+dy, i*m+j);
}
}
else if(k==)// 下
{
if(farm[map[dx][dy]][]&&farm[map[i][j]][]){
merge(dx*m+dy, i*m+j);
}
}
}
}
}
int cnt=;
for(i=; i<n*m; ++i)
if(f[i]==i)
++cnt;
printf("%d\n", cnt);
}
return ;
}
最新文章
- 达夫设备(Duff&#39;s Device)
- EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射
- php之JavaScript
- iOS 随记
- app设计需注意的
- C# 循环语句 for循环
- IT男的”幸福”生活";续7
- android实现可拖动按钮
- grep简单常用的语法介绍
- Away3d 骨骼动画优化
- ASP.NET Core Authorization
- JPG、PNG和GIF图片的基本原理及优化方法
- vertx的HttpServer模块
- Android greenDAO 数据库 简单学习之基本使用
- 关于单元测试时加载spring-context.xml文件的问题
- python数据结构与算法第九天【选择排序】
- 第十八单元 nginx服务
- jquery中ajax的写法
- HDU 4725 The Shortest Path in Nya Graph(构图)
- 嵌入式C编程代码优化笔记
热门文章
- 51nod 算法马拉松17 解题报告 以后不能赛中写题解(查逐梦者抄袭本人代码...
- plsql循环的简单实例
- javaEE(15)_Servlet过滤器
- C# 读App.config配置文件[2]: .Net Core框架
- CSS3的border-image
- 【java】 field 和 variable 区别及相关术语解释
- 【php】 自带的过滤机制
- 面向对象之多态,property
- appIcon
- LeetCode(99) Recover Binary Search Tree