회원가입
로그인
Toggle navigation
문제
문제
전체 문제
문제 출처
단계별로 풀어보기
알고리즘 분류
추가된 문제
문제 순위
문제
푼 사람이 한 명인 문제
아무도 못 푼 문제
최근 제출된 문제
최근 풀린 문제
랜덤
출처
ICPC
Olympiad
한국정보올림피아드
한국정보올림피아드시․도지역본선
전국 대학생 프로그래밍 대회 동아리 연합
대학교 대회
카카오 코드 페스티벌
Coder's High
ICPC
Regionals
World Finals
Korea Regional
Africa and the Middle East Regionals
Europe Regionals
Latin America Regionals
North America Regionals
South Pacific Regionals
문제집
대회
채점 현황
게시판
그룹
더 보기
재채점 기록
블로그
도움말
전체
공지
자유
질문
오타/오역/요청
게시판 공지
홍보
업데이트
solved.ac
글쓰기
질문 도움말
자주묻는 질문
음 왜 메모리 초과일까요
16402번 - 제국
hero00
2년 전
0
유니온 파인드로 풀었는데, 최적화가 더 필요한건가요..?
import java.io.*; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet; public class PS_16402 { static final String SEPARATOR = " "; static final String RESULT_SEPARATOR = ","; static final char LINE_END = '\n'; static final int A_WIN = 1; static final String PREFIX = "Kingdom of "; static final int B_WIN = 2; static HashMap <String, String> parentMap = new HashMap<>(); static HashMap <String, Integer> count = new HashMap<>(); static String find(final String s) { String next = parentMap.get(s); if (next.equals(s)) return s; parentMap.replace(next, find(next)); return next; } static void union(final String a, final String b) { String A = find(parentMap.get(a)); String B = find(parentMap.get(b)); if (A.equals(B)) { parentMap.replace(a, a); parentMap.replace(A, a); int x = count.get(a); count.replace(a, x, x + count.get(A)); count.replace(A, 0); } else { parentMap.replace(B, A); int [] x = {count.get(A), count.get(B)}; count.replace(A, x[0], x[0] + x[1]); count.replace(B, 0); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); String [] input = br.readLine().split(" "); int N = Integer.parseInt(input[0]); int M = Integer.parseInt(input[1]); int warType; String k1, k2; while (N-- > 0) { k1 = br.readLine().split(SEPARATOR)[2]; parentMap.put(k1, k1); count.put(k1, 1); } while (M-- > 0) { input = br.readLine().split(RESULT_SEPARATOR); k1 = input[0].split(SEPARATOR)[2]; k2 = input[1].split(SEPARATOR)[2]; warType = Integer.parseInt(input[2]); switch (warType) { case A_WIN: union(k1, k2); break; case B_WIN: union(k2, k1); break; } } br.close(); int count = 0; TreeSet <String> result = new TreeSet<>(); for (String name: parentMap.keySet()) { if (name.equals(parentMap.get(name))) { count++; result.add(name); } } sb.append(count).append(LINE_END); for (String name: result) sb.append(PREFIX).append(name).append(LINE_END); bw.write(sb.toString()); bw.flush(); bw.close(); } }
hero00
2년 전
0
음... 동일하게 C++로 풀었는데 얘는 또 AC네요;;
댓글을 작성하려면
로그인
해야 합니다.
hero00 2년 전
유니온 파인드로 풀었는데, 최적화가 더 필요한건가요..?