Skip to content

Commit bc3ca2c

Browse files
authored
Merge pull request #91 from AlgorithmWithGod/khj20006
[20250212] BOJ / G2 / 불켜기 / 권혁준
2 parents ba5e28e + 5fc64d8 commit bc3ca2c

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
```java
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
class Main {
7+
8+
// IO field
9+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
11+
static StringTokenizer st;
12+
13+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
14+
static int nextInt() {return Integer.parseInt(st.nextToken());}
15+
static long nextLong() {return Long.parseLong(st.nextToken());}
16+
static void bwEnd() throws Exception {bw.flush();bw.close();}
17+
18+
// Additional field
19+
static int[] d;
20+
static boolean[] can;
21+
static boolean[] on;
22+
static int N, M;
23+
static int[] root;
24+
static int[] cnt;
25+
static List<Integer>[] V;
26+
27+
public static void main(String[] args) throws Exception {
28+
29+
ready();
30+
solve();
31+
32+
bwEnd();
33+
}
34+
35+
static void ready() throws Exception{
36+
37+
nextLine();
38+
N = nextInt();
39+
M = nextInt();
40+
d = new int[] {-N,-1,1,N};
41+
42+
can = new boolean[N*N];
43+
on = new boolean[N*N];
44+
root = new int[N*N];
45+
cnt = new int[N*N];
46+
V = new List[N*N];
47+
for(int i=0;i<N*N;i++) {
48+
root[i] = i;
49+
V[i] = new ArrayList<>();
50+
}
51+
52+
for(int i=0;i<M;i++) {
53+
nextLine();
54+
int a = nextInt(), b = nextInt(), c = nextInt(), d = nextInt();
55+
int from = coord(a-1,b-1), to = coord(c-1,d-1);
56+
V[from].add(to);
57+
}
58+
59+
}
60+
61+
static void solve() throws Exception{
62+
63+
cnt[0] = 1;
64+
can[0] = true;
65+
on[0] = true;
66+
boolean change;
67+
68+
do {
69+
70+
change = false;
71+
72+
for(int i=0;i<N*N;i++) {
73+
if(!can[i]) continue;
74+
for(int j:V[i]) {
75+
if(!on[j]) {
76+
change = true;
77+
on[j] = true;
78+
for(int k=0;k<4;k++) {
79+
int g = j+d[k];
80+
if(0<=g&&g<N*N && adj(j,g) && on[g]) {
81+
int x = f(j), y = f(g);
82+
if(x != y) {
83+
cnt[y] += cnt[x];
84+
root[x] = y;
85+
}
86+
}
87+
}
88+
}
89+
}
90+
}
91+
92+
for(int i=1;i<N*N;i++) {
93+
if(!on[i] || can[i]) continue;
94+
if(f(0) == f(i)) {
95+
change = true;
96+
can[i] = true;
97+
}
98+
}
99+
100+
}while(change);
101+
102+
int ans = 0;
103+
for(int i=0;i<N*N;i++) if(on[i]) ans++;
104+
bw.write(ans+"\n");
105+
106+
}
107+
108+
static boolean adj(int x, int y) {
109+
if(Math.abs(x-y) == 1) {
110+
if(x/N != y/N) return false;
111+
}
112+
return true;
113+
}
114+
static int coord(int x, int y) {return x*N+y;}
115+
static int f(int x) {return x==root[x] ? x : (root[x] = f(root[x]));}
116+
117+
}
118+
119+
```

0 commit comments

Comments
 (0)