티스토리 뷰
728x90
문제링크
https://www.acmicpc.net/problem/6118
6118번: 숨바꼭질
문제 재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재석이는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자. 재서기는 수혀니가 1번 헛간부터 찾을 것을 알고 있다. 모든 헛간은 M(1<= M <= 50,000)개의 양방향 길로 이어져 있고, 그 양 끝을 A_i 와 B_i(1<= A_i <= N; 1 <= B_i <= N; A_i != B_i)로 나타낸
www.acmicpc.net
시작지점인 1번에서 가장 멀리있는 지점의 거리와 같은 거리를 갖는 지점중 가장 낮은 번호를 갖는 지점 그리고 같은 거리를 갖는 지점의 개수를 출력하는 문제입니다.
문제에서 길은 양방향으로 취급하기 때문에 인접행렬 형식으로 길 정보를 저장하였습니다.
다익스트라 알고리즘을 활용하였고 모든 길은 가중치가 동일하기 때문에 가중치를 따로 저장하지 않았습니다.
다익스트라 알고리즘으로 1번 시작위치에서 모든 지점까지 가는 길이를 각각 구하고 마지막에 정렬을 통해 가장 먼 거리를 구합니다.
마지막에 순차탐색으로 각 지점까지의 거리와 가장먼거리를 비교해서 가장 먼저 같은 위치의 번호, 같은 위치의 개수를 구하고 정답을 출력하였습니다.
#include <iostream> #include <algorithm> #include <math.h> #include <string> #include <queue> using namespace std; #define MAX_M 50001 #define MAX_N 20001 #define INF 987654321 //typedef struct NODE { // int weight; // int end; //}; vector<int> edge[MAX_M]; int dist[MAX_N]; int start_node, N, M; //int index[4][2] = { {1,0}, {0,1}, {-1,0}, {0,-1} };//아래 오른쪽 위 왼쪽 순서대로 void dijkstra() { priority_queue<pair<int , int>> pq; pq.push({ 0, start_node }); int now_node; while (pq.empty() == false) { now_node = pq.top().second; pq.pop(); for (int i = 0; i < edge[now_node].size(); i++) { int new_value = dist[now_node] + 1; int before_value = dist[edge[now_node][i]]; if (new_value < before_value) { dist[edge[now_node][i]] = new_value; pq.push({-1*new_value, edge[now_node][i] }); } } } } bool compare(pair<int , int> a, pair<int,int> b) { return a.second < b.second; } void debug() { } void clear() { } int main() { int max_value; scanf("%d %d", &N, &M); start_node = 1; int start, end, weight; for (int i = 0; i < M; i++) { scanf("%d %d", &start, &end); edge[start].push_back(end); edge[end].push_back(start); } for (int i = 1; i <= N; i++) { dist[i] = INF; } dist[1] = 0; dijkstra(); max_value = *max_element(dist + 1, dist + N); int count = 0; int idx; for (int i = 1; i <= N; i++) { if (dist[i] == max_value) { count++; if (count == 1) idx = i; } } printf("%d %d %d", idx, max_value, count); }
'알고리즘' 카테고리의 다른 글
백준 9205 - 맥주 마시면서 걸어가기 (0) | 2020.02.09 |
---|---|
백준 2178 - 미로 탐색 (0) | 2020.02.09 |
백준 - 1012 유기농 배추 (0) | 2020.02.06 |
백준 2667번 - 단지번호붙이기 DFS풀이 (0) | 2020.02.04 |
백준 1652번 - 누울 자리를 찾아라 (0) | 2020.01.26 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 알고리즘
- 언리얼 빌드
- Jenkins Build Periodically
- 언리얼 사용자 정의 구조체
- 백준
- 언리얼
- 유니티
- 젠킨스
- C++
- Jenkins
- 안드로이드
- c언어 기초
- UHT
- 알고리즘기초
- Add Node
- c언어강의
- 유니티 직소퍼즐 구현
- 깃 허브 오류 해결
- 빌드 주기
- refusing to run with root privileges
- 언리얼 기초
- 젠킨스 에이전트 연결
- Unreal Header Tool
- 안드로이드 구글맵
- C언어기초
- 깃 용량문제
- 구글맵
- Connecting Jenkins Agent
- Connecting Jenkins
- dfs
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함