Benny has a spacious farm land to irrigate. The farm land is a rectangle, and is divided into a lot of samll squares. Water pipes are placed in these squares. Different square has a different type of pipe. There are 11 types of pipes, which is marked from A to K, as Figure 1 shows.
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.
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
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.
2 2 DK HF 3 3 ADC FJK IHE -1 -1
23
题意:能相连的地只需要打一口井,求出最少需要挖多少口井(水井在每块农田的正中央),才能使所有农田都被灌溉
题意:使用并查集,如果两块农地水管能相连则在同一个集合中。此题需要自己判断连通关系,即两个水管是否可以连接到一起,也是本题的难点。
#include<iostream> #include<algorithm> using namespace std; int set[55*55]; char map[55][55]; char c[12][5]={"1010","1001","0110","0101", "1100","0011","1011","1110", "0111","1101","1111"}; void Init_set(int x){ for(int i=0;i<x;i++) set[i]=i; } int find(int x){ int r=x; while(set[r]!=r) r=set[r]; return r; } void merge(int a,int b){ a=find(a); b=find(b); if(a!=b) set[b]=a; } int main(){ int m; int n; while(cin>>m>>n,(m!=-1&&n!=-1)){ for(int i=0;i<m;i++) cin>>map[i]; Init_set(n*m); for(int i=0;i<m;i++) for(int j=0;j<n;j++){ //竖直方向 if(j>0&&c[map[i][j]-'A'][2]=='1'&&c[map[i][j-1]-'A'][3]=='1') merge(i*n+j,i*n+j-1); //水平方向 if(i>0&&c[map[i][j]-'A'][0]=='1'&&c[map[i-1][j]-'A'][1]=='1') merge(i*n+j,(i-1)*n+j); } int ans=0; for(int i=0;i<m*n;i++) if(set[i]==i) ans++; cout<<ans<<endl; } return 0; }