class Unionfind { public: vector data; Unionfind(size_t size) : data(size, -1) { } bool connect(size_t x, size_t y) { x = root(x); y = root(y); if (x != y) { if (data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = (int)x; } return x != y; } inline bool same(size_t x, size_t y) { return root(x) == root(y); } inline size_t root(size_t x) { return (size_t)(data[x] < 0 ? x : data[x] = root(data[x])); } inline int size(size_t x) { return -data[root(x)]; } }; int H,W,HW; { rd(H,W); HW = H*W; Unionfind uf(HW+1); register int cnt;cnt = HW+1; REP(p, HW){ int c;rd(c); if (c == 0) cnt -= uf.connect(p, HW); else{ if (W<=p && !uf.same(p-W, HW)) cnt -= uf.connect(p, p-W); if (p%W>0 && !uf.same(p-1, HW)) cnt -= uf.connect(p, p-1); } } wt(cnt-1); }