[C++] 백준 1939 중량제한

2021. 2. 9. 14:39·Algorithm/Baekjoon
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int MaxNum = 100001;
int n, m, start, finish;

bool visited[MaxNum];
vector<pair<int, int>> nodes[MaxNum];

bool BFS(int cost);

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	int lowCost, highCost, maxCost;


	cin >> n >> m;

	for (int i = 0; i < m; i++)
	{
		int temp1, temp2, temp3;
		cin >> temp1 >> temp2 >> temp3;
		nodes[temp1].push_back({ temp2, temp3 });
		nodes[temp2].push_back({ temp1, temp3 });
		maxCost = max(maxCost, temp3);
	}
	cin >> start >> finish;

	lowCost = 0; highCost = maxCost;
	while (lowCost <= highCost)	//이진 탐색
	{
		memset(visited, false, sizeof(visited));

		int midCost = (lowCost + highCost) / 2;

		if (BFS(midCost) == true)
		{
			lowCost = midCost + 1;
		}
		else
		{
			highCost = midCost - 1;
		}
	}

	cout << highCost;
}

bool BFS(int cost)	//너비 우선 탐색
{
	queue<int> q;
	q.push(start);
	visited[start] = true;

	while (!q.empty())
	{
		int currNode = q.front();	//현재 너비에 있는 것을 순차적으로 검색
		q.pop();	//검색한 곳은 삭제

		if (currNode == finish) return true;

		for (int i = 0; i < nodes[currNode].size(); i++)
		{
			int nextNode = nodes[currNode][i].first;
			int weight = nodes[currNode][i].second;

			if (!visited[nextNode] && cost <= weight)	//방문한 곳이 아니고 cost가 가중치보다 적을때
			{
				visited[nextNode] = true;
				q.push(nextNode);	//다음 너비에 있는 노드들을 저장
			}
		}
	}

	return false;
}

 

중량의 최대최소는 이진탐색으로 찾고 건너는 다리는 너비우선탐색을 하며 하나씩 검사한다.

저작자표시 (새창열림)

'Algorithm > Baekjoon' 카테고리의 다른 글

[C++] 백준 2250 트리의 높이와 너비  (0) 2021.02.11
[C++] 백준 1991 트리 순회  (0) 2021.02.10
[C++] 백준 2110 공유기 설치  (0) 2021.02.05
[C++] 백준 1236 성 지키기  (0) 2021.02.04
[C++] 백준 1668 트로피 진열  (0) 2021.02.04
'Algorithm/Baekjoon' 카테고리의 다른 글
  • [C++] 백준 2250 트리의 높이와 너비
  • [C++] 백준 1991 트리 순회
  • [C++] 백준 2110 공유기 설치
  • [C++] 백준 1236 성 지키기
chanheess
chanheess
'왜' 그렇게 했는가?에 대한 생각으로 공부 및 작업의 저장관리
왜 그렇게 생각했는가?'왜' 그렇게 했는가?에 대한 생각으로 공부 및 작업의 저장관리
  • chanheess
    왜 그렇게 생각했는가?
    chanheess
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Backend Programming
      • Game Programming
        • Unreal
        • DirectX
      • C++
        • Memo
        • Basic
        • Effective Modern
      • Java
      • Algorithm
        • Memo
        • Baekjoon
        • Programmers
        • HackerRank, LeetCode
      • Data Structure
      • Design Pattern
      • Etc
        • Memo
        • Daily Log
        • Book
  • 최근 글

  • 최근 댓글

  • 태그

    dp
    SpringSecurity
    Java
    오블완
    알고리즘
    위클리 챌린지
    spring
    c++ 기초 플러스
    티스토리챌린지
    백준
    프로그래머스
    JWT
    dfs
    JPA
  • hELLO· Designed By정상우.v4.10.0
chanheess
[C++] 백준 1939 중량제한

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.