結果

問題 No.697 池の数はいくつか
ユーザー chocoruskchocorusk
提出日時 2020-10-04 01:12:01
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,190 ms / 6,000 ms
コード長 1,421 bytes
コンパイル時間 2,234 ms
コンパイル使用メモリ 77,668 KB
実行使用メモリ 115,296 KB
最終ジャッジ日時 2024-04-25 20:53:18
合計ジャッジ時間 16,746 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
54,036 KB
testcase_01 AC 124 ms
54,168 KB
testcase_02 AC 127 ms
54,188 KB
testcase_03 AC 126 ms
54,320 KB
testcase_04 AC 123 ms
53,868 KB
testcase_05 AC 124 ms
54,292 KB
testcase_06 AC 128 ms
54,176 KB
testcase_07 AC 127 ms
54,268 KB
testcase_08 AC 112 ms
52,952 KB
testcase_09 AC 126 ms
54,480 KB
testcase_10 AC 125 ms
54,024 KB
testcase_11 AC 124 ms
54,016 KB
testcase_12 AC 126 ms
54,200 KB
testcase_13 AC 114 ms
52,920 KB
testcase_14 AC 127 ms
54,288 KB
testcase_15 AC 126 ms
54,280 KB
testcase_16 AC 128 ms
54,556 KB
testcase_17 AC 128 ms
53,904 KB
testcase_18 AC 125 ms
54,352 KB
testcase_19 AC 126 ms
54,072 KB
testcase_20 AC 132 ms
54,300 KB
testcase_21 AC 124 ms
53,908 KB
testcase_22 AC 116 ms
52,872 KB
testcase_23 AC 128 ms
54,168 KB
testcase_24 AC 428 ms
62,788 KB
testcase_25 AC 423 ms
62,828 KB
testcase_26 AC 435 ms
62,524 KB
testcase_27 AC 419 ms
62,628 KB
testcase_28 AC 427 ms
62,792 KB
testcase_29 AC 1,126 ms
115,012 KB
testcase_30 AC 1,179 ms
114,916 KB
testcase_31 AC 1,186 ms
115,296 KB
testcase_32 AC 1,184 ms
115,036 KB
testcase_33 AC 1,179 ms
115,160 KB
testcase_34 AC 1,190 ms
114,900 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		PrintWriter out=new PrintWriter(System.out);
		String[] hw=scanner.nextLine().split(" ");
		int h=Integer.parseInt(hw[0]);
		int w=Integer.parseInt(hw[1]);
		String[] s=new String[h];
		int cnt=0;
		for(int i=0; i<h; i++) {
			s[i]=scanner.nextLine();
			for(int j=0; j<w; j++) {
				if(s[i].charAt(2*j)=='1') cnt++;
			}
		}
		UnionFind uf=new UnionFind(h*w);
		for(int i=0; i<h; i++) {
			for(int j=0; j<w; j++) {
				if(s[i].charAt(2*j)=='0') continue;
				int x=i*w+j;
				if(i+1<h && s[i+1].charAt(2*j)=='1') {
					if(uf.unite(x, (i+1)*w+j)) cnt--;
				}
				if(j+1<w && s[i].charAt(2*j+2)=='1') {
					if(uf.unite(x,  i*w+j+1)) cnt--;
				}
			}
		}
		out.println(cnt);
		out.close();
		scanner.close();
	}
}
class UnionFind{
	int n;
	int[] par;
	int cmp;
	public UnionFind(int n) {
		this.n=n;
		this.par=new int[n];
		Arrays.fill(this.par, -1);
		this.cmp=n;
	}
	public int find(int x) {
		if(par[x]<0) return x;
		return par[x]=find(par[x]);
	}
	public boolean unite(int x, int y) {
		x=find(x);
		y=find(y);
		if(x==y) {
			return false;
		}
		cmp--;
		if(par[x]>par[y]) {
			int tmp=x;
			x=y;
			y=tmp;
		}
		par[x]+=par[y];
		par[y]=x;
		return true;
	}
	public boolean same(int x, int y) {
		return find(x)==find(y);
	}
}
0