250x250
Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Properties
- GC로그수집
- 힙덤프
- 스택
- alter
- BFS
- html
- 리소스모니터링
- union_find
- set
- string
- Union-find
- 큐
- NIO
- math
- 스프링부트
- Java
- date
- map
- scanner
- spring boot
- javascript
- Calendar
- CSS
- List
- dfs
- JPA
- deque
- sql
- priority_queue
Archives
- Today
- Total
매일 조금씩
백준 1976번: 여행 가자 본문
728x90
반응형


Union-find를 활용한 문제이므로 각 도시들이 연결되었는지 확인 하려면 root가 같은지만 확인하면 된다.
root가 같으면 다른 도시들을 거쳐서라도 갈수 있기 때문.
*** Union-find 개념 ***
https://gimmesome.tistory.com/34?category=1103655
[1주차] Union-find
학교에서 알고리즘을 배울때도 Union-find는 따로 배운적은 없고 기억을 더듬어 보면... 다른 알고리즘에 포함되어 있는 걸로 배웠던것 같다. Union-find 강의를 보면서 관련 문제들을 풀어보다가 Union-find를 활..
gimmesome.tistory.com
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, M;
int arr[200];
int findParent(int num) {
if (arr[num] < 0)
return num;
int parent = findParent(arr[num]);
arr[num] = parent;
return parent;
}
void merge(int iParent, int jParent) {
if (abs(arr[iParent]) >= abs(arr[jParent])) {
arr[iParent] += arr[jParent];
arr[jParent] = iParent;
}
else {
arr[jParent] += arr[iParent];
arr[iParent] = jParent;
}
}
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0); //cin 실행속도 향상
cin >> N >> M;
for (int i = 0; i <= N; i++) {
arr[i] = -1;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int connected;
cin >> connected;
if (connected) {
int iParent = findParent(i);
int jParent = findParent(j);
if (iParent == jParent)
continue;
merge(iParent, jParent);
}
}
}
int root;
bool possible = true;
for (int i = 0; i < M; i++) {
int city;
cin >> city;
//첫 도시에서 root를 구해놔야 나중에 비교할게 있음
if(i == 0)
root = findParent(city-1);
else {
if (root != findParent(city-1)) {
possible = false;
break;
}
}
}
if (possible)
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
728x90
반응형
'알고리즘' 카테고리의 다른 글
백준 16562번: 친구비 (0) | 2020.03.13 |
---|---|
백준 10775번: 공항 (0) | 2020.03.09 |
백준 1717번: 집합의 표현 (0) | 2020.03.08 |
백준 5218번: 알파벳 거리 (0) | 2020.02.16 |
백준 5555번: 반지 (0) | 2020.02.16 |