๋ฌธ์
ํด๋น ํฌ์คํ ์ ๋ฐฑ์ค์ 2468๋ฒ ์์ ์์ญ ์ ์ ๊ทผ๊ณผ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ค๋ช ํ ๊ธ ์ ๋๋ค.
์ ๋ต ์์ค ์ฝ๋๋ฅผ ํ์ธํ์๋ ค๋ฉด solve url ์์ ํ์ธ ๊ฐ๋ฅํฉ๋๋ค.
2468๋ฒ: ์์ ์์ญ
์ฌ๋๋ฐฉ์ฌ์ฒญ์์๋ ๋ง์ ๋น๊ฐ ๋ด๋ฆฌ๋ ์ฅ๋ง์ฒ ์ ๋๋นํด์ ๋ค์๊ณผ ๊ฐ์ ์ผ์ ๊ณํํ๊ณ ์๋ค. ๋จผ์ ์ด๋ค ์ง์ญ์ ๋์ด ์ ๋ณด๋ฅผ ํ์ ํ๋ค. ๊ทธ ๋ค์์ ๊ทธ ์ง์ญ์ ๋ง์ ๋น๊ฐ ๋ด๋ ธ์ ๋ ๋ฌผ์ ์ ๊ธฐ์ง ์๋
www.acmicpc.net
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์ด๋ค ๋ฐฉ์์ผ๋ก ์ ๊ทผํด์ผ ํ๋์ง๋ฅผ ๋จผ์ ์๊ฐํด๋ณด์.
๋ฌธ์ ์ ๊ทผ
์ด๋ฒ ๋ฌธ์ ๋ BFS, DFS ๋ชจ๋ ์ฌ์ฉํ ์ ์๋ ๋ฌธ์ ์ด๋ค.
๊ฐ์๋์ 1๋ถํฐ ์์์ ์ต๋๊น์ง ๊ฐ๊ฐ ์กฐ์ฌํ๋ ๋ฐฉ๋ฒ์ ์ทจํ๋ฉด ๋๋ค.
์ ๋ต ์ฝ๋
public class Main {
static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] nm = br.readLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);
visited = new boolean[n + 1];
for(int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
while(m-- > 0) {
String[] uv = br.readLine().split(" ");
int u = Integer.parseInt(uv[0]);
int v = Integer.parseInt(uv[1]);
graph.get(u).add(v);
graph.get(v).add(u);
}
int answer = 0;
for (int i = 1; i <= n; i++) {
if(dfsByRecursive(i)) {
answer += 1;
}
}
bw.write(String.valueOf(answer));
bw.flush();
bw.close();
}
private static boolean dfsByRecursive(int x) {
if(visited[x]) {
return false;
}else {
visited[x] = true;
int size = graph.get(x).size();
for (int i = 0; i < size; i++) {
int value = graph.get(x).get(i);
if(!visited[value]){
dfsByRecursive(value);
}
}
return true;
}
}
private static boolean bfs(int x) {
Queue<Integer> queue = new LinkedList<>();
if(visited[x]) {
return false;
}else {
queue.add(x);
visited[x] = true;
while(!queue.isEmpty()) {
x = queue.remove();
int size = graph.get(x).size();
for(int i = 0; i < size; i++) {
int value = graph.get(x).get(i);
if(!visited[value]) {
queue.add(value);
visited[value] = true;
}
}
}
return true;
}
}
}
์ ๋ต ์์ค ์ฝ๋๋ฅผ ํ์ธํ์๋ ค๋ฉด solve url ์์ ํ์ธ ๊ฐ๋ฅํฉ๋๋ค.
๋ก๊ทธ์ธ
www.acmicpc.net
๋๊ธ