USACO 2.1 The Castle

Type:无向图的连通分支

描述:一个m*n的城堡,有一些墙分隔了若干房间,求房间数,及最大的房间,和拆掉一堵墙后能得到的最大房间。

思路:先DFS,然后遍历m*n,根据最西边、最南边的规则,只考虑去掉东边北边的墙。

Process:

写的很垃圾,wa6次,刚开始“Choose the optimal wall to remove from the set of optimal walls by choosing the wall farthest to the west (and then, if still tied, farthest to the south). Name that wall by naming the module that borders it on either the west or south, along with a direction of N or E giving the location of the wall with respect to the module.” 就没看准,一直在这个地方错。还有记录分支的rm[]开小了,wa了一次。

代码
1 /*
2 ID: superbi1
3 LANG: C
4 TASK: castle
5  */
6
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdlib.h>
10  #define MAX(x,y) ((x)>(y)?(x):(y))
11  #define MIN(x,y) ((x)<(y)?(x):(y))
12  #define NL 51
13
14 FILE *in;
15 FILE *out;
16  int m, n;
17  int msk[NL][NL];
18 int flg[NL][NL];
19 //1表示有墙,0没有墙
20 int stp[16][4] = { {0, 0, 0, 0},
21 {1, 0, 0, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}, {0, 0, 1, 0},
22 {1, 0, 1, 0}, {0, 1, 1, 0}, {1, 1, 1, 0}, {0, 0, 0, 1},
23 {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 0, 1}, {0, 0, 1, 1},
24 {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1, 1, 1}
25 };
26 int dir[4][2] = {
27 {0, -1}, {-1, 0}, {0, 1}, {1, 0}
28 };
29 int rm[NL*NL];
30
31 void DFS(int I, int K, int cop)
32 {
33 int t;
34 int x, y;
35 rm[cop]++;
36 for (t=0; t<4; t++) {
37 if (!stp[msk[I][K]][t]) {
38 x = I + dir[t][0];
39 y = K + dir[t][1];
40 if (x>=1 && x <=n
41 && y>=1 && y<=m
42 && !flg[x][y]) {
43 flg[x][y] = cop;
44 DFS(x, y, cop);
45 }
46 }
47 }
48 }
49
50 int main()
51 {
52 int I, K;
53 int lct, cop;
54 int x, y, t;
55 int max;
56 int pmax, px, py;
57 char dt;
58 in = fopen("castle.in", "r");
59 out = fopen("castle.out", "w");
60 fscanf(in, "%d%d", &m, &n);
61 for (I=1; I<=n; I++) {
62 for (K=1; K<=m; K++) {
63 fscanf(in, "%d", &lct);
64 msk[I][K] = lct;
65 }
66 }
67 memset(flg, 0, sizeof(flg));
68 cop = 0;
69 memset(rm, 0, sizeof(rm));
70 for (I=1; I<=n; I++) {
71 for (K=1; K<=m; K++) {
72 if (!flg[I][K]) {
73 cop++;
74 flg[I][K] = cop;
75 DFS(I, K, cop);
76 }
77 }
78 }
79 fprintf(out, "%d\n", cop);
80 max = 0;
81 px = py = 0;
82 for (I=1; I<=cop; I++)
83 if (rm[I] > max) max = rm[I];
84 fprintf(out, "%d\n", max);
85 pmax = max;
86 for (I=1; I<=n; I++) {
87 for (K=1; K<=m; K++) {
88 for (t=1; t<3; t++) {
89 if (stp[msk[I][K]][t]) {
90 x = I+dir[t][0];
91 y = K+dir[t][1];
92 if (x>=1 && x<=n
93 && y>=1 && y<=m
94 && flg[x][y] != flg[I][K]) {
95 //大于和等于要分开考虑
96 if (rm[flg[x][y]]+rm[flg[I][K]] > pmax) {
97 pmax = rm[flg[x][y]]+rm[flg[I][K]];
98 px = I;
99 py = K;
100 dt = t==1?'N':'E';
101 }else if (rm[flg[x][y]]+rm[flg[I][K]] == pmax) {
102 if (K < py) {
103 px = I; py = K;
104 dt = t==1?'N':'E';
105 }else if (K==py && I>px) {
106 px = I;
107 dt = t==1?'N':'E';
108 }
109 }
110 }
111 }
112 }
113 }
114 }
115 fprintf(out, "%d\n%d %d %c\n", pmax, px, py, dt);
116 return 0;
117 }
118

 



posted @ 2010-05-29 17:04  superbin  阅读(514)  评论(0编辑  收藏  举报