<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bellman–Ford Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<atom:link href="https://lycos7560.com/tag/bellman-ford/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>생각의 흐름을 타고 다니며 만드는 블로그</description>
	<lastBuildDate>Thu, 16 Mar 2023 19:39:26 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://lycos7560.com/wp-content/uploads/2022/11/cropped-cropped-cropped-log-1-150x150-1-80x80.png</url>
	<title>Bellman–Ford Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>백준 1219번 (오민식의 고민, C++, Bellman–Ford) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 18:38:37 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1219]]></category>
		<category><![CDATA[1219번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Bellman–Ford]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[그래프 이론]]></category>
		<category><![CDATA[그래프 탐색]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[길찾기]]></category>
		<category><![CDATA[반례]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 1219]]></category>
		<category><![CDATA[백준 1219번]]></category>
		<category><![CDATA[벨만-포드]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[예제]]></category>
		<category><![CDATA[오민식의 고민]]></category>
		<category><![CDATA[추가 반례]]></category>
		<category><![CDATA[추가 예제]]></category>
		<category><![CDATA[추가반례]]></category>
		<category><![CDATA[추가예제]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[틀렸습니다!]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33149</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 1219번 '오민식의 고민' 문제에 대한 글입니다. Bellman–Ford 알고리즘을 이용하여 해결하였습니다. (This is BAEKJOON's 1219, "오민식의 고민" Solved using Bellman–Ford algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/">백준 1219번 (오민식의 고민, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>


				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-00285461      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차 테이블						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#오민식의-고민" class="uagb-toc-link__trigger">오민식의 고민</a><li class="uagb-toc__list"><a href="#주의-사항" class="uagb-toc-link__trigger">주의 사항</a><li class="uagb-toc__list"><a href="#통과된-코드" class="uagb-toc-link__trigger">통과된 코드</a><li class="uagb-toc__list"><a href="#추가-반례" class="uagb-toc-link__trigger">추가 반례</a></ol>					</div>
									</div>
				</div>
			


<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">오민식의 고민</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/1219" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1219</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure id="problem-info" class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">시간 제한</th><th class="has-text-align-left" data-align="left">메모리 제한</th><th class="has-text-align-left" data-align="left">제출</th><th class="has-text-align-left" data-align="left">정답</th><th class="has-text-align-left" data-align="left">맞힌 사람</th><th class="has-text-align-left" data-align="left">정답 비율</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">2 초</td><td class="has-text-align-left" data-align="left">128 MB</td><td class="has-text-align-left" data-align="left">10997</td><td class="has-text-align-left" data-align="left">2142</td><td class="has-text-align-left" data-align="left">1250</td><td class="has-text-align-left" data-align="left">16.718%</td></tr></tbody></table></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">문제</h2>



<p class="has-medium-font-size wp-block-paragraph">오민식은 세일즈맨이다. </p>



<p class="has-medium-font-size wp-block-paragraph">오민식의 회사 사장님은 오민식에게 물건을 최대한 많이 팔아서 최대 이윤을 남기라고 했다.</p>



<p class="has-medium-font-size wp-block-paragraph">오민식은 고민에 빠졌다. 어떻게 하면 최대 이윤을 낼 수 있을까?</p>



<p class="has-medium-font-size wp-block-paragraph">이 나라에는 N개의 도시가 있다. 도시는 0번부터 N-1번까지 번호 매겨져 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">오민식의 여행은&nbsp;A도시에서 시작해서 B도시에서 끝난다.</p>



<p class="has-medium-font-size wp-block-paragraph">오민식이 이용할 수 있는 교통수단은 여러 가지가 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">오민식은 모든 교통수단의 출발 도시와 도착 도시를 알고 있고, 비용도 알고 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">게다가, 오민식은 각각의 도시를 방문할 때마다 벌 수 있는 돈을 알고있다. </p>



<p class="has-medium-font-size wp-block-paragraph">이 값은 도시마다 다르며, 액수는 고정되어있다. 또, 도시를 방문할 때마다 그 돈을 벌게 된다.</p>



<p class="has-medium-font-size wp-block-paragraph">오민식은 도착 도시에 도착할 때, 가지고 있는 돈의 액수를 최대로 하려고 한다. </p>



<p class="has-medium-font-size wp-block-paragraph">이 최댓값을 구하는 프로그램을 작성하시오.</p>



<p class="has-medium-font-size wp-block-paragraph">오민식이 버는 돈보다 쓰는 돈이 많다면, 도착 도시에 도착할 때 가지고 있는 돈의 액수가 음수가 될 수도 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">또, 같은 도시를 여러 번 방문할 수 있으며, 그 도시를 방문할 때마다 돈을 벌게 된다. </p>



<p class="has-medium-font-size wp-block-paragraph">모든 교통 수단은 입력으로 주어진 방향으로만 이용할 수 있으며, 여러 번 이용할 수도 있다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 도시의 수 N과 시작 도시, 도착 도시 그리고 교통 수단의 개수 M이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">둘째 줄부터 M개의 줄에는 교통 수단의 정보가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">교통 수단의 정보는 “시작 끝 가격”과 같은 형식이다. </p>



<p class="has-medium-font-size wp-block-paragraph">마지막 줄에는 오민식이 각 도시에서 벌 수 있는 돈의 최댓값이 0번 도시부터 차례대로 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">N과 M은 50보다 작거나 같고, 돈의 최댓값과 교통 수단의 가격은 1,000,000보다 작거나 같은 음이 아닌 정수이다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 도착 도시에 도착할 때, 가지고 있는 돈의 액수의 최댓값을 출력한다. </p>



<p class="has-medium-font-size wp-block-paragraph">만약 오민식이 도착 도시에 도착하는 것이 불가능할 때는 &#8220;gg&#8221;를 출력한다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">그리고, 오민식이 도착 도시에 도착했을 때 돈을 무한히 많이 가지고 있을 수 있다면 &#8220;Gee&#8221;를 출력한다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 7
0 1 13
1 2 17
2 4 20
0 3 22
1 3 4747
2 0 10
3 4 10
0 0 0 0 0</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-32</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 5
0 1 10
1 2 10
2 3 10
3 1 10
2 4 10
0 10 10 110 10</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Gee</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3 0 2 3
0 1 10
1 0 10
2 1 10
1000 1000 47000</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">gg</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 4</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">2 0 1 2
0 1 1000
1 1 10
11 11</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 4</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Gee</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 5</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 0 0 1
0 0 10
7</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 5</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">7</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 6</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 7
0 1 13
1 2 17
2 4 20
0 3 22
1 3 4747
2 0 10
3 4 10
8 10 20 1 100000</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 6</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">99988</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출처</h2>



<ul class="wp-block-list">
<li>문제를 번역한 사람:&nbsp;<a href="https://www.acmicpc.net/user/baekjoon" target="_blank" rel="noreferrer noopener">baekjoon</a></li>



<li>잘못된 조건을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a></li>



<li>데이터를 추가한 사람:&nbsp;<a href="https://www.acmicpc.net/user/gkgg123" target="_blank" rel="noreferrer noopener">gkgg123</a>,&nbsp;<a href="https://www.acmicpc.net/user/sait2000" target="_blank" rel="noreferrer noopener">sait2000</a></li>



<li>문제의 오타를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/jh05013" target="_blank" rel="noreferrer noopener">jh05013</a>,&nbsp;<a href="https://www.acmicpc.net/user/typhoon" target="_blank" rel="noreferrer noopener">typhoon</a></li>
</ul>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">알고리즘 분류</h2>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/11" target="_blank" rel="noreferrer noopener">그래프 탐색</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/10" target="_blank" rel="noreferrer noopener">벨만–포드</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<h1 class="wp-block-heading">주의 사항</h1>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1600" height="1408" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230213_032410192.jpg" alt="" class="wp-image-33158" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230213_032410192.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230213_032410192-300x264.jpg 300w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230213_032410192-768x676.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230213_032410192-1536x1352.jpg 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">순환이 도착 지점에 영향을 줄 수 있도록 많은 시도가 필요하다. </p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1009" height="384" src="https://lycos7560.com/wp-content/uploads/2023/02/image-68.png" alt="" class="wp-image-33159" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-68.png 1009w, https://lycos7560.com/wp-content/uploads/2023/02/image-68-300x114.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-68-768x292.png 768w" sizes="(max-width: 1009px) 100vw, 1009px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">통과된 코드</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;vector>

using namespace std;

constexpr int MAXN = 50;

constexpr long long int INF = -INT64_MAX;

long long int disArr[MAXN];

int N, S, D, M, V, U, W, G[MAXN];

bool check = false;

vector&lt;pair&lt;int, int>> graph[MAXN];

int main()
{
    ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
    // cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
    cin.tie(NULL);
    std::cout.tie(NULL);

    cin >> N >> S >> D >> M;

    // 교통 수단을 입력받는다.
    for (int i = 0; i &lt; M; i++) {
        cin >> V >> U >> W;
        // 단방향 교통수단 출발, 도착, 비용
        graph[V].push_back(make_pair(U, -W));
    }

    // 도시에서 버는 비용입력
    for (int i = 0; i &lt; N; i++) cin >> G[i];

    fill(disArr, disArr + MAXN, INF);

    disArr[S] = G[S];

    // N번 이후부터는 순환 체크
    // 순환이 있는지 충분히 확인
    for (int k = 1; k &lt;= N * 2; k++) { 
        for (int i = 0; i &lt; N; i++) { // 시작 정점
            for (int j = 0; j &lt; graph[i].size(); j++) {
                int v = graph[i][j].first; // 도착점
                int weight = graph[i][j].second; // 가중치

                if (disArr[i] == -INF) disArr[v] = -INF; // 출발지가 순환이라면 도착지도 순환
                else if (disArr[i] != INF &amp;&amp; disArr[i] + weight + G[v] > disArr[v]) {
                    disArr[v] = disArr[i] + weight + G[v]; // 업데이트

                    if (k >= N) disArr[v] = -INF; // 순환찾기
                }
            }
        }
    }

    if (disArr[D] == -INF) cout &lt;&lt; "Gee"; // 순환에 포함
    else if (disArr[D] == INF) cout &lt;&lt; "gg"; // 도착 불가능 
    else cout &lt;&lt; disArr[D];

    return 0;

}</pre>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1202" height="268" src="https://lycos7560.com/wp-content/uploads/2023/02/image-67.png" alt="" class="wp-image-33151" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-67.png 1202w, https://lycos7560.com/wp-content/uploads/2023/02/image-67-300x67.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-67-768x171.png 768w" sizes="(max-width: 1202px) 100vw, 1202px" /></figure>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">추가 반례</h1>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 A</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 6
0 1 10000
1 2 0
2 1 0
1 3 0
0 3 0
3 4 0
0 0 1 0 0</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 A</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Gee</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 B</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 0 0
1 2 3 4 5</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 B</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 C</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">50 0 49 50
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
5 6 0
6 7 0
7 8 0
8 9 0
9 10 0
10 11 0
11 12 0
12 13 0
13 14 0
14 15 0
15 16 0
16 17 0
17 18 0
18 19 0
19 20 0
20 21 0
21 22 0
22 23 0
23 24 0
24 25 0
25 26 0
26 27 0
27 28 0
28 29 0
29 30 0
30 31 0
31 32 0
32 33 0
33 34 0
34 35 0
35 36 0
36 37 0
37 38 0
38 39 0
39 40 0
40 41 0
41 42 0
42 43 0
43 44 0
44 45 0
45 46 0
46 47 0
47 48 0
48 49 0
49 0 0
1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 C</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Gee</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 D</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 5
0 1 0
1 2 0
2 3 0
3 1 0
0 4 0
1 1 1 1 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 D</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">2</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 E</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 0 3 4
0 1 0
0 3 5
1 2 0
2 1 0
0 5 5 10</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 E</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 F</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 0 4 5
0 1 10
1 2 10
2 3 10
3 1 10
2 4 10
0 10 10 110 10</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 F</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Gee</pre>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/">백준 1219번 (오민식의 고민, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 1865번 (웜홀, C++, Bellman–Ford) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 14:53:28 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1865]]></category>
		<category><![CDATA[1865번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Bellman–Ford]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[그래프 이론]]></category>
		<category><![CDATA[그래프 탐색]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[길찾기]]></category>
		<category><![CDATA[반례]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 1865]]></category>
		<category><![CDATA[백준 1865번]]></category>
		<category><![CDATA[벨만-포드]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[예제]]></category>
		<category><![CDATA[웜홀]]></category>
		<category><![CDATA[추가 반례]]></category>
		<category><![CDATA[추가 예제]]></category>
		<category><![CDATA[추가반례]]></category>
		<category><![CDATA[추가예제]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[틀렸습니다!]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33135</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 1865번 '웜홀' 문제에 대한 글입니다. Bellman–Ford 알고리즘을 이용하여 해결하였습니다. (This is an article about the 'Warmhole' problem in BAEKJOON 1865. Solved using Bellman–Ford algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/">백준 1865번 (웜홀, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>


				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-f9b53ff3      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차 테이블						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#웜홀" class="uagb-toc-link__trigger">웜홀</a><li class="uagb-toc__list"><a href="#풀이-방법" class="uagb-toc-link__trigger">풀이 방법</a><li class="uagb-toc__list"><a href="#풀이에-도움되는-글" class="uagb-toc-link__trigger">풀이에 도움되는 글</a><li class="uagb-toc__list"><a href="#통과된-코드" class="uagb-toc-link__trigger">통과된 코드</a></ol>					</div>
									</div>
				</div>
			


<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">웜홀</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/1865" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1865</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure id="problem-info" class="wp-block-table"><table><thead><tr><th>시간 제한</th><th>메모리 제한</th><th>제출</th><th>정답</th><th>맞힌 사람</th><th>정답 비율</th></tr></thead><tbody><tr><td>2 초</td><td>128 MB</td><td>36111</td><td>8293</td><td>5117</td><td>21.896%</td></tr></tbody></table></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">문제</h2>



<p class="has-medium-font-size wp-block-paragraph">때는 2020년, 백준이는 월드나라의 한 국민이다. </p>



<p class="has-medium-font-size wp-block-paragraph">월드나라에는 N개의 지점이 있고 N개의 지점 사이에는 M개의 도로와 W개의 웜홀이 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">(단 도로는 방향이 없으며 웜홀은 방향이 있다.) </p>



<p class="has-medium-font-size wp-block-paragraph">웜홀은 시작 위치에서 도착 위치로 가는 하나의 경로인데, </p>



<p class="has-medium-font-size wp-block-paragraph">특이하게도 도착을 하게 되면 시작을 하였을 때보다 시간이 뒤로 가게 된다.</p>



<p class="has-medium-font-size wp-block-paragraph">웜홀 내에서는 시계가 거꾸로 간다고 생각하여도 좋다.</p>



<p class="has-medium-font-size wp-block-paragraph">시간 여행을 매우 좋아하는 백준이는 한 가지 궁금증에 빠졌다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">한&nbsp;지점에서 출발을 하여서 시간여행을 하기 시작하여 다시 출발을 하였던 위치로 돌아왔을 때, </p>



<p class="has-medium-font-size wp-block-paragraph">출발을 하였을 때보다 시간이 되돌아가 있는 경우가 있는지 없는지 궁금해졌다. </p>



<p class="has-medium-font-size wp-block-paragraph">여러분은 백준이를 도와 이런 일이 가능한지 불가능한지 구하는 프로그램을 작성하여라.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫 번째 줄에는 테스트케이스의 개수 TC(1 ≤ TC ≤ 5)가 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">그리고 두 번째 줄부터 TC개의 테스트케이스가 차례로 주어지는데 각 테스트케이스의 첫 번째 줄에는 </p>



<p class="has-medium-font-size wp-block-paragraph">지점의 수 N(1 ≤ N ≤ 500), 도로의 개수 M(1 ≤ M ≤ 2500), 웜홀의 개수 W(1 ≤ W ≤ 200)이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">그리고 두 번째 줄부터 M+1번째 줄에 도로의 정보가 주어지는데 각 도로의 정보는 S, E, T 세 정수로 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">S와 E는 연결된 지점의 번호, T는 이 도로를 통해 이동하는데 걸리는 시간을 의미한다. </p>



<p class="has-medium-font-size wp-block-paragraph">그리고 M+2번째 줄부터 M+W+1번째 줄까지 웜홀의 정보가 S, E, T 세 정수로 주어지는데 </p>



<p class="has-medium-font-size wp-block-paragraph">S는 시작 지점, E는 도착 지점, T는 줄어드는 시간을 의미한다. </p>



<p class="has-medium-font-size wp-block-paragraph">T는 10,000보다 작거나 같은 자연수 또는 0이다.</p>



<p class="has-medium-font-size wp-block-paragraph">두 지점을 연결하는 도로가 한 개보다 많을 수도 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">지점의 번호는 1부터 N까지 자연수로 중복 없이 매겨져 있다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">TC개의 줄에 걸쳐서 만약에 시간이 줄어들면서 출발 위치로 돌아오는 것이 가능하면 YES, 불가능하면 NO를 출력한다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">NO
YES</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출처</h2>



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/category/2" target="_blank" rel="noreferrer noopener">Olympiad</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/106" target="_blank" rel="noreferrer noopener">USA Computing Olympiad</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/155" target="_blank" rel="noreferrer noopener">2006-2007 Season</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/158" target="_blank" rel="noreferrer noopener">USACO December 2006 Contest</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/697" target="_blank" rel="noreferrer noopener">Gold</a>&nbsp;1번</p>



<ul class="wp-block-list">
<li>데이터를 추가한 사람:&nbsp;<a href="https://www.acmicpc.net/user/artichoke42" target="_blank" rel="noreferrer noopener">artichoke42</a>,&nbsp;<a href="https://www.acmicpc.net/user/jh05013" target="_blank" rel="noreferrer noopener">jh05013</a></li>
</ul>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">알고리즘 분류</h2>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/10" target="_blank" rel="noreferrer noopener">벨만–포드</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<h1 class="wp-block-heading">풀이 방법</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1430" height="1920" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230212_233800523.jpg" alt="" class="wp-image-33140" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230212_233800523.jpg 1430w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230212_233800523-223x300.jpg 223w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230212_233800523-768x1031.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230212_233800523-1144x1536.jpg 1144w" sizes="(max-width: 1430px) 100vw, 1430px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">풀이에 도움되는 글</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/board/view/72995" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/board/view/72995</a>   &lt;-  jh05013의 설명</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">이 문제에는 여러 우여곡절의 역사가 있습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">그래서인지 시작점이 어디라는 언급이 전혀 없는데도 인터넷에 있는 거의 모든 풀이가 1을 시작 정점으로 잡고, </p>



<p class="has-medium-font-size wp-block-paragraph">원래 dist[v] != INF이 들어가야 최단거리가 제대로 구해지는데 이걸 오히려 빼버리는 데다가, </p>



<p class="has-medium-font-size wp-block-paragraph">왜 이걸 빼야 정답을 받는지는 설명을 안 하고 있습니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="has-medium-font-size wp-block-heading"><strong>1. 백준이가 출발을 어디서 하는가?</strong></h2>



<p class="has-medium-font-size wp-block-paragraph">아무데서나 출발할 수 있습니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="has-medium-font-size wp-block-heading"><strong>2. 왜 시작 정점을 1로 정해도 풀리는가?</strong></h2>



<p class="has-medium-font-size wp-block-paragraph">방금도 언급했듯이 인터넷에 있는 거의 모든 풀이는&nbsp;아래의 &#8220;코드 1&#8243;처럼 구현하고 있습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">그런데도 맞았습니다!!를 받는데,&nbsp;그건&nbsp;<strong>잘못된 구현이 오히려 이 문제에서는&nbsp;올바른 풀이가 되어서</strong>&nbsp;그렇습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">바로 dist[v] != INF를 검사하지 않는 것입니다. &#8220;코드 2&#8243;와 비교해 보세요.</p>



<p class="has-medium-font-size wp-block-paragraph">코드 1은&nbsp;&#8220;dist[v] == INF&#8221;를 &#8220;v를 방문하지 않았다&#8221;가 아니라 &#8220;v를 방문했고,&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">v까지의 최단거리가 INF다&#8221;로 인식하고 있습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">그래서 이 코드는 이미 처음부터 모든 정점을 방문한 걸로&nbsp;착각을 하게 되는데, </p>



<p class="has-medium-font-size wp-block-paragraph">덕분에 음수 사이클이 어디에 있든 항상 도달이 가능하기 때문에 정답을 받습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">어차피 모든 정점을 처음부터 방문하니까,&nbsp;dist[1] = 0은 이 코드에서는&nbsp;아무 의미가 없습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">dist[3] = 0을 하거나, 아예 이 줄을 빼도 맞습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">그렇다면 코드 1이 항상 코드 2보다 좋은 코드이냐? 그렇지 않습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">코드 1에서는 어떤 정점이 실제로 도달 가능한 정점인지 알 수 없기 때문에,&nbsp;<strong><u>코드 1은&nbsp;올바른 벨만 포드 구현이 아닙니다.</u></strong>&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">(즉 v가 실제로 도달 불가능한 정점이더라도 dist[v] != INF일 수 있습니다.)&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">단지 그 정보가 이 문제에서는 필요 없기 때문에 맞는 것뿐이고, </p>



<p class="has-medium-font-size wp-block-paragraph">만약 문제가 &#8220;각 점까지의 최단거리를 구해라&#8221;였다면 코드 2처럼 하는 것이 좋습니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="has-medium-font-size wp-block-heading"><strong>2-1. 코드 2는 왜 틀리는가?</strong></h3>



<p class="has-medium-font-size wp-block-paragraph">아래의 &#8220;코드 2&#8243;처럼 구현했다면 오답 처리가 될 것입니다. </p>



<p class="has-medium-font-size wp-block-paragraph">틀려야 되는 이유는 시작 정점으로부터 도달할 수 없는 음수 사이클을 못 찾기 때문입니다. </p>



<p class="has-medium-font-size wp-block-paragraph">다시 말하면, 이렇게 구현했을 경우 한 점에서만 출발하면 안 됩니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="has-medium-font-size wp-block-heading"><strong>2-2. 파이썬 float(&#8216;inf&#8217;)</strong></h3>



<p class="has-medium-font-size wp-block-paragraph">float(&#8216;inf&#8217;)에 음수를 더해도 여전히 float(&#8216;inf&#8217;)이기 때문에, 이 경우에는 거리 갱신이 이루어지지 않습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">그래서 이 경우는 코드 2와 똑같이 동작합니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="has-medium-font-size wp-block-heading"><strong>2-3. 그럼 제 강의 자료가 틀린 건가요?</strong></h3>



<p class="has-medium-font-size wp-block-paragraph">당장&nbsp;<a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" target="_blank" rel="noreferrer noopener">위키피디아만 봐도</a>&nbsp;dist[v] != INF 같은 게 안 보이지만, 그렇다고 그 자료가 틀린 건 아닙니다.</p>



<p class="has-medium-font-size wp-block-paragraph">일반적으로, 알고리즘 설명이나 수도코드에서 ∞ 같은 게 나오면 &#8220;아주 큰 수&#8221;가 아니라 진짜로 무한대입니다. </p>



<p class="has-medium-font-size wp-block-paragraph">파이썬으로 치면 float(&#8216;inf&#8217;)와 같습니다. </p>



<p class="has-medium-font-size wp-block-paragraph">진짜로 무한대면 dist[v]가&nbsp;∞인지 여부와 관계없이&nbsp;거리 갱신을 다 해도 상관없습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">실제로 구현할 때는&nbsp;&#8220;무한히 큰 int&#8221;같은 건 없으니까, </p>



<p class="has-medium-font-size wp-block-paragraph">도달을 아직 못 한 점에서는&nbsp;거리 갱신을 안 하는 식으로 우회하는 것일 뿐입니다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="has-medium-font-size wp-block-heading"><strong>3. 두 번째 방법으로 구현했으면&nbsp;어떻게 풀어야 하는가?</strong></h3>



<p class="has-medium-font-size wp-block-paragraph">두 가지 방법이&nbsp;있습니다.</p>



<ul class="wp-block-list">
<li>시작 정점이 한 개일 필요는 없습니다. 모든 정점에서 &#8220;동시에&#8221; 시작할 수 있습니다. <br>그러려면&nbsp;거리 배열 전체를&nbsp;INF가 아닌 0으로 초기화하고 벨만 포드를 돌리면 됩니다.</li>



<li>그래도 꼭 시작 정점이 단 하나였으면 좋겠다고 생각하신다면, N+1번째 &#8220;가짜 정점&#8221;을 만들어서 <br>나머지 모든 정점으로 가중치 0의 간선을 긋고, 시작 정점을 N+1로 잡으면 됩니다. <br>그러면 모든 정점이 도달 가능하므로 음수 사이클이 어디에 있든 항상 찾을 수 있습니다.</li>
</ul>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">코드 1
INF = 2000000000
모든 dist[v] = INF
dist[1] = 0
N-1번 반복:
  모든 v에 대해:
    모든 간선에 대해 최단거리 갱신
모든 v에 대해:
  모든 간선에 대해 최단거리 갱신
  갱신이 한 번이라도 일어났으면 true

===

코드 2
INF = 2000000000
모든 dist[v] = INF
dist[1] = 0
N-1번 반복:
  dist[v] != INF인 모든 v에 대해:
    모든 간선에 대해 최단거리 갱신
dist[v] != INF인 모든 v에 대해:
  모든 간선에 대해 최단거리 갱신
  갱신이 한 번이라도 일어났으면 true
</pre>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">통과된 코드</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;vector>

using namespace std;

constexpr int MAXN = 501;

int disArr[MAXN];

int TC, N, M, W, S, E, T;

vector&lt;pair&lt;int, int>> graph[MAXN];

bool BellmanFord()
{
	cin >> N >> M >> W;

	vector&lt;pair&lt;int, int>> graph[MAXN];

	// 도로의 정보를 입력받는다.
	for (int i = 0; i &lt; M; i++) {
		cin >> S >> E >> T;
		// 양방향
		graph[S].push_back(make_pair(E, T));
		graph[E].push_back(make_pair(S, T));
	}

	// 웜홀의 정보를 입력받는다.
	for (int i = 0; i &lt; W; i++) {
		cin >> S >> E >> T;
		// 단방향
		graph[S].push_back(make_pair(E, -T));
	}

	// 출발은 어디에새 해도 상관이 없다.
	fill(disArr, disArr + MAXN, 0);

	// (모든 정점의 수 - 1) 번 확인한다.
	// N 번은 순환 체크
	for (int k = 1; k &lt;= N; k++) {
		for (int i = 1; i &lt;= N; i++) { // 시작 정점
			for (int j = 0; j &lt; graph[i].size(); j++) {
				int v = graph[i][j].first; // 도착점
				int weight = graph[i][j].second; // 가중치
	
				// 시작 임시 배열의 가중치가 도착지의 가중치보다 크다면
				if (disArr[i] + weight &lt; disArr[v]) {
					disArr[v] = disArr[i] + weight;

					// K == N 일때 새로 업데이트 된다는 의미
					if (k == N) return true; // 순환이 있음
					
				}
			}
		}
	}

	return false;
	// 순환이 없음
}

int main()
{
	ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
	// cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
	cin.tie(NULL);
	std::cout.tie(NULL);

	cin >> TC;

	for (int i = 0; i &lt; TC; i++) {

		if (BellmanFord()) cout &lt;&lt; "YES\n";
		else cout &lt;&lt; "NO\n";

	}

	return 0;
}</pre>



<div style="height:39px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1037" height="138" src="https://lycos7560.com/wp-content/uploads/2023/02/image-66.png" alt="" class="wp-image-33138" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-66.png 1037w, https://lycos7560.com/wp-content/uploads/2023/02/image-66-300x40.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-66-768x102.png 768w" sizes="(max-width: 1037px) 100vw, 1037px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/">백준 1865번 (웜홀, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 1738번 (골목길, C++, Bellman–Ford) / 추가 반례 [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sat, 11 Feb 2023 01:19:36 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1738]]></category>
		<category><![CDATA[1738번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Bellman–Ford]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[골목길]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[그래프 이론]]></category>
		<category><![CDATA[그래프 탐색]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[길찾기]]></category>
		<category><![CDATA[반례]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 1738]]></category>
		<category><![CDATA[백준 1738번]]></category>
		<category><![CDATA[벨만-포드]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[예제]]></category>
		<category><![CDATA[추가 반례]]></category>
		<category><![CDATA[추가 예제]]></category>
		<category><![CDATA[추가반례]]></category>
		<category><![CDATA[추가예제]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[틀렸습니다]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33119</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 1738번 '골목길' 문제에 대한 글입니다. Bellman–Ford 알고리즘을 이용하여 해결하였습니다. (This is an article about the 'Alley Road' problem in BAEKJOON 1738. Solved using Bellman–Ford algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/">백준 1738번 (골목길, C++, Bellman–Ford) / 추가 반례 [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>


				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-56e81e2a      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차 테이블						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#골목길" class="uagb-toc-link__trigger">골목길</a><li class="uagb-toc__list"><a href="#주의-사항" class="uagb-toc-link__trigger">주의 사항</a><li class="uagb-toc__list"><a href="#통과된-코드" class="uagb-toc-link__trigger">통과된 코드</a><li class="uagb-toc__list"><a href="#추가-반례" class="uagb-toc-link__trigger">추가 반례</a></ol>					</div>
									</div>
				</div>
			


<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">골목길</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/1738" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1738</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure id="problem-info" class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">시간 제한</th><th class="has-text-align-left" data-align="left">메모리 제한</th><th class="has-text-align-left" data-align="left">제출</th><th class="has-text-align-left" data-align="left">정답</th><th class="has-text-align-left" data-align="left">맞힌 사람</th><th class="has-text-align-left" data-align="left">정답 비율</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">2 초</td><td class="has-text-align-left" data-align="left">128 MB</td><td class="has-text-align-left" data-align="left">5531</td><td class="has-text-align-left" data-align="left">932</td><td class="has-text-align-left" data-align="left">552</td><td class="has-text-align-left" data-align="left">17.824%</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">문제</h2>



<p class="has-medium-font-size wp-block-paragraph">민승이는&nbsp;놀러가기 위해 집을 나섰다. </p>



<p class="has-medium-font-size wp-block-paragraph">민승이네 집에서 코레스코 콘도까지 가기 위해서는 복잡하게 얽혀있는 골목길들을 통과해야 한다.</p>



<p class="has-medium-font-size wp-block-paragraph">그런데, 어떤 길에는 깡패가 서식하고 있어, 그 길을 지나게 되면 깡패에게 일정한 양의 금품을 갈취당하게 된다. </p>



<p class="has-medium-font-size wp-block-paragraph">그런가하면, 어떤 길에는 지나가던 행인들이 흘리고 간 금품들이 떨어져 있어, 그 길을 지나게 되면 일정한 양의 금품을 획득하게 된다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">한 번 지나간 길을 다시 방문하더라도 금품을 갈취당하거나 획득한다.</p>



<p class="has-medium-font-size wp-block-paragraph">골목길의 연결 상태와, 각 골목길을 지날 때 갈취당하거나 획득하게 되는 금품의 양이 주어졌을 때, </p>



<p class="has-medium-font-size wp-block-paragraph">민승이가 최대한 유리한 경로를 따라 집에서 코레스코 콘도까지 가기 위해서는 어떻게 해야 하는지 출력하는 프로그램을 작성하시오.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">보유 중인 금품의 양이 음수가 될 수 있다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">최대한 유리한 경로 또는 최적의 경로는 민승이네 집에서 출발하여 코레스코 콘도에 도착하는 경로 중 금품의 양이 최대가 되는 경로이다.&nbsp;</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 골목길들이 교차하는 지점의 개수&nbsp;n (2 ≤ n ≤ 100)과 </p>



<p class="has-medium-font-size wp-block-paragraph">골목길의 개수&nbsp;m&nbsp;(1 ≤ m ≤ 20,000)&nbsp;이 차례로 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">이어지는 m개의 행에 각각의 골목길을 나타내는 세 정수 u, v, w가 차례로 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">이는 u번 교차점에서 v번 교차점으로 이동할 수 있는 골목길이 나있다는 의미이다. </p>



<p class="has-medium-font-size wp-block-paragraph">즉, 주어지는 골목길들은 기본적으로 모두 일방통행로이다.</p>



<p class="has-medium-font-size wp-block-paragraph">w (0 ≤ |w| ≤ 1,000)는 이 길을 지날 때 갈취당하거나 획득하게 되는 금품의 양이다. </p>



<p class="has-medium-font-size wp-block-paragraph">음수는 갈취, 양수는 획득을 뜻한다.</p>



<p class="has-medium-font-size wp-block-paragraph">골목길의 교차점 번호는 1이상 n이하의 정수이다. </p>



<p class="has-medium-font-size wp-block-paragraph">민승이네 집은 1번 교차점에 있고, 이곳 코레스코 콘도는 n번 교차점에 있다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">최적의 경로를 구할 수 있다면 민승이네 집부터 코레스코 콘도까지 가는 동안 거치게 되는 </p>



<p class="has-medium-font-size wp-block-paragraph">교차점들의 번호를 공백 하나를 사이에 두고 차례로 출력하면 된다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">그런데, 경우에 따라서는 최적의 경로라는 것이 존재하지 않는 상황이 발생한다. </p>



<p class="has-medium-font-size wp-block-paragraph">어떠한 경우에 그런 상황이 발생하는지 생각해 보자.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">그러한 경우에는 -1을 출력하도록 한다.</p>



<p class="has-medium-font-size wp-block-paragraph">최적의 경로가 여러 개 존재할 때는 아무거나 출력해도 된다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 7
1 2 3
1 3 4
3 1 -7
2 3 2
3 4 1
4 2 -5
4 5 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 3 4 5</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 7
1 2 3
1 3 4
3 1 -7
2 3 2
3 4 1
4 2 -2
4 5 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출처</h2>



<ul class="wp-block-list">
<li>문제를 번역한 사람:&nbsp;<a href="https://www.acmicpc.net/user/author10" target="_blank" rel="noreferrer noopener">author10</a></li>



<li>빠진 조건을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/kcm1700" target="_blank" rel="noreferrer noopener">kcm1700</a></li>
</ul>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">알고리즘 분류</h2>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/10" target="_blank" rel="noreferrer noopener">벨만–포드</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<figure class="wp-block-embed is-type-wp-embed is-provider-어제와-내일의-나-그-사이의-이야기 wp-block-embed-어제와-내일의-나-그-사이의-이야기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="fCwu8tviMy"><a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/">알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/embed/#?secret=3wXyJtRRUm#?secret=fCwu8tviMy" data-secret="fCwu8tviMy" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<h1 class="wp-block-heading">주의 사항</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">이 문제는 Bellman–Ford 알고리즘을 사용할 때 사이클이 있다고 해서 무조건 -1 을 출력하면 안된다.</p>



<p class="has-medium-font-size wp-block-paragraph">해당 사이클이 <strong>최적의 경로에 영향이 있는지 확인</strong>이 필요하다.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1409" height="1920" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_101542736.jpg" alt="" class="wp-image-33132" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_101542736.jpg 1409w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_101542736-220x300.jpg 220w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_101542736-768x1047.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_101542736-1127x1536.jpg 1127w" sizes="(max-width: 1409px) 100vw, 1409px" /></figure>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">통과된 코드</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;vector>

using namespace std;

constexpr long long int INF = INT64_MAX;

constexpr int MAXN = 101;

vector&lt;pair&lt;int, int>> graph[MAXN];

long long int disArr[MAXN];

// N : 지점의 개수, M : 골목길의 개수
int N, M, u, v, w;

int trace[MAXN];

int main()
{

	ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
	// cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
	cin.tie(NULL);
	std::cout.tie(NULL);

	cin >> N >> M;

	fill(disArr, disArr + MAXN, INF);

	disArr[1] = 0;

	for (int i = 0; i &lt; M; i++) {
		cin >> u >> v >> w;
		// 단방향
		graph[u].push_back(make_pair(v, -w));
	}


	// (모든 정점의 수 - 1) 번 확인한다.
	// N 번은 순환 체크
	for (int k = 1; k &lt;= N; k++) {
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 0; j &lt; graph[i].size(); j++) {

				int u = i; // 시작점
				int v = graph[i][j].first; // 도착점
				int weight = graph[i][j].second; // 가중치

				// 만약 임시 배열이 무한대가 아니고 &amp;&amp;
				// 시작 임시 배열의 가중치가 도착지의 가중치보다 크다면
				if (disArr[u] != INF &amp;&amp; disArr[u] + weight &lt; disArr[v]) {
					disArr[v] = disArr[u] + weight;
					trace[v] = u;

					// K == N 일때 새로 업데이트 된다는 의미는 
					// 사이클에 포함되거나 사이클에서 도착 지점으로 도달 가능
					// 다음의 disArr[N] == -INF 코드를 통하여 영향이 있는 경로인지 판별 
					if (k == N) disArr[v] = -INF;
					// -INF로 더이상 업데이트를 막는다.
				}
			}
		}
	}

	if (disArr[N] == INF || disArr[N] == -INF) cout &lt;&lt; "-1";
	else {
		// 경로를 역으로 추적한다.
		int now = N;
		vector&lt;int> myV;
		while (now != 0) {
			myV.push_back(now);
			now = trace[now]; 
		}

		for (auto it = myV.rbegin(); it != myV.rend(); ++it) cout &lt;&lt; *it &lt;&lt; " ";

	}

	return 0;
}</pre>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1032" height="372" src="https://lycos7560.com/wp-content/uploads/2023/02/image-65.png" alt="" class="wp-image-33121" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-65.png 1032w, https://lycos7560.com/wp-content/uploads/2023/02/image-65-300x108.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-65-768x277.png 768w" sizes="(max-width: 1032px) 100vw, 1032px" /></figure>



<div style="height:150px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">추가 반례</h1>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 A</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 4
1 2 1
2 3 1
3 2 1
1 4 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 A</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 4</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 B</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">7 11
1 2 3
1 3 4
3 1 -7
2 3 2
3 4 1
4 2 -5
4 7 1
4 5 1
5 6 2
6 5 3
6 7 -1000</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 B</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 C</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 7
1 2 1
2 3 1
3 4 1
4 5 1
1 5 10
1 2 50
2 5 80</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 C</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 5</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 D</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 5
1 2 -1
2 3 1
3 4 1
4 2 1
2 5 -1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 D</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 E</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 4
1 4 3
2 3 1
3 2 1
4 2 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 E</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 4</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 F</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 5
1 2 1
2 3 1
3 4 1
3 2 1
4 1 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 F</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 G</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 5
1 2 1
2 3 1
3 4 1
3 1 1
4 1 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 G</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 H</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 5
1 2 1
2 3 1
3 4 1
4 3 1
2 5 1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 H</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 5</pre>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/">백준 1738번 (골목길, C++, Bellman–Ford) / 추가 반례 [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</title>
		<link>https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/</link>
					<comments>https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 10 Feb 2023 18:17:44 +0000</pubDate>
				<category><![CDATA[기타]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Bellman–Ford]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Dijkstra]]></category>
		<category><![CDATA[DP]]></category>
		<category><![CDATA[DynamicProgramming]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[다이나믹 프로그래밍]]></category>
		<category><![CDATA[다익스트라]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[벨만-포드]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33044</guid>

					<description><![CDATA[<p>벨만-포드 (Bellman–Ford Algorithm) 알고리즘을 정리한 내용의 글입니다. (This article summarizes Bellman-Ford algorithm.)</p>
<p>The post <a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/">알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>


				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-0138b7d4      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차 테이블						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#벨만-포드-bellmanford-algorithm-알고리즘" class="uagb-toc-link__trigger">벨만-포드 (Bellman–Ford Algorithm) 알고리즘</a><ul class="uagb-toc__list"><li class="uagb-toc__list"><a href="#작동하는-과정" class="uagb-toc-link__trigger">작동하는 과정</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#주의-사항" class="uagb-toc-link__trigger">주의 사항</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#구현-코드" class="uagb-toc-link__trigger">구현 코드</a><ul class="uagb-toc__list"><li class="uagb-toc__list"><a href="#코드-c" class="uagb-toc-link__trigger">코드 C++</a></li></ul><li class="uagb-toc__list"><a href="#dijkstra-알고리즘-vs-bellmanford-알고리즘" class="uagb-toc-link__trigger">Dijkstra 알고리즘 vs Bellman–Ford 알고리즘</a><ul class="uagb-toc__list"><li class="uagb-toc__list"><a href="#1-가중치의-차이" class="uagb-toc-link__trigger">1. 가중치의 차이</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#2-시간-복잡도의-차이" class="uagb-toc-link__trigger">2. 시간 복잡도의 차이</a></ul></ul></ol>					</div>
									</div>
				</div>
			


<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="has-large-font-size wp-block-heading">벨만-포드 (Bellman–Ford Algorithm) 알고리즘</h1>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">Bellman-Ford 알고리즘은 (Richard Bellman과 Lester Ford의 이름)</p>



<p class="has-medium-font-size wp-block-paragraph">가중 그래프에서 정점과 다른 모든 정점 사이의 최단 경로를 찾는 데 사용되는 최단 경로 알고리즘입니다.</p>



<p class="has-medium-font-size wp-block-paragraph">간단하게 말하면<strong> <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-ast-global-color-8-color">한 정점에서 다른 정점까지의 최단 거리를 구하는 알고리즘</mark></strong>입니다.</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">작동하는 과정</h2>



<p class="wp-block-paragraph"><a href="https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/" target="_blank" rel="noreferrer noopener">https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="551" height="327" src="https://lycos7560.com/wp-content/uploads/2023/02/image-57.png" alt="" class="wp-image-33065" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-57.png 551w, https://lycos7560.com/wp-content/uploads/2023/02/image-57-300x178.png 300w" sizes="(max-width: 551px) 100vw, 551px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph"><strong>1단계:</strong>&nbsp;출발 정점을 0으로 둡니다. </p>



<p class="has-medium-font-size wp-block-paragraph">출발 정점의 거리를 제외하고 모든 거리를 무한으로 초기화합니다.&nbsp;</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<figure class="wp-block-image size-full"><img decoding="async" width="548" height="330" src="https://lycos7560.com/wp-content/uploads/2023/02/image-60.png" alt="" class="wp-image-33068" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-60.png 548w, https://lycos7560.com/wp-content/uploads/2023/02/image-60-300x181.png 300w" sizes="(max-width: 548px) 100vw, 548px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph"><strong>2단계:</strong>&nbsp;모든 정점을 다음 순서로 처리합니다</p>



<p class="has-medium-font-size wp-block-paragraph">(B, E), (D, B), (B, D), (A, B), (A, C), (D, C), (B, C), (E, D) </p>



<p class="has-medium-font-size wp-block-paragraph">모든 모서리가 처음으로 처리될 때 다음과 같은 거리를 얻습니다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">첫 번째 행은 초기의 거리를 보여줍니다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">두 번째 행은 가장자리 (B, E), (D, B), (B, D) 및 (A, B)가 처리될 때 거리를 보여줍니다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">세 번째 행은 (A, C)가 처리될 때의 거리를 보여줍니다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">네 번째 행은 (D, C), (B, C) 및 (E, D) 를 처리한 거리를 보여줍니다.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<figure class="wp-block-image size-full"><img decoding="async" width="658" height="321" src="https://lycos7560.com/wp-content/uploads/2023/02/image-61.png" alt="" class="wp-image-33075" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-61.png 658w, https://lycos7560.com/wp-content/uploads/2023/02/image-61-300x146.png 300w" sizes="(max-width: 658px) 100vw, 658px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph"><strong>3단계:</strong>&nbsp;첫 번째 반복은 최대 1 정점 길이의 모든 최단 경로를 제공합니다.</p>



<p class="has-medium-font-size wp-block-paragraph">모든 정점이 두 번째로 처리 될 때 다음과 같은 거리를 얻습니다 (마지막 행은 최종 값을 나타냅니다).</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<p class="has-medium-font-size wp-block-paragraph"><strong>4단계:</strong>&nbsp;두 번째 반복은 최대 2 개의 가장자리 길이인 모든 최단 경로를 제공합니다.</p>



<p class="has-medium-font-size wp-block-paragraph">알고리즘은 모든 정점을 2번 더 처리합니다.</p>



<p class="has-medium-font-size wp-block-paragraph">두 번째 반복 후에는 거리가 최소화되므로 </p>



<p class="has-medium-font-size wp-block-paragraph">세 번째 및 네 번째 반복에서는 거리가 업데이트되지 않습니다.</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">주의 사항</h2>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">Bellman-Ford 알고리즘을 사용할 경우 아래와 같은 음의 가중치 주기를 주의해야 합니다.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="364" height="346" src="https://lycos7560.com/wp-content/uploads/2023/02/image-63.png" alt="" class="wp-image-33094" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-63.png 364w, https://lycos7560.com/wp-content/uploads/2023/02/image-63-300x285.png 300w" sizes="(max-width: 364px) 100vw, 364px" /><figcaption class="wp-element-caption"><a href="https://www.techiedelight.com/determine-negative-weight-cycle-graph/" target="_blank" rel="noreferrer noopener">https://www.techiedelight.com/determine-negative-weight-cycle-graph/</a></figcaption></figure>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">위의 예제는 1 -&gt; 2 -&gt; 3 순서를 계속 반복하면 가중치가  계속 줄어듭니다. (잘못된 결과)</p>



<p class="has-medium-font-size wp-block-paragraph">위와 같은 상황에서는 Bellman-Ford 알고리즘으로 답을 구할 수 없습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">그래프에 음의 가중치 주기가 포함되어 있는지 확인하려면 </p>



<p class="has-medium-font-size wp-block-paragraph">Bellman-Ford 알고리즘 이후에 모든 간선을 다시 한번 확인합니다.</p>



<p class="has-medium-font-size wp-block-paragraph"><strong>만약 업데이트가 일어난다면 음의 가중치가 포함되어있다는 의미</strong> 입니다.</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">구현 코드</h2>



<p class="has-medium-font-size wp-block-paragraph">백준 11657번 &#8216;타임머신&#8217; 문제를  Bellman-Ford 알고리즘 코드 해결</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-어제와-내일의-나-그-사이의-이야기 wp-block-embed-어제와-내일의-나-그-사이의-이야기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="Baal9ouENg"><a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/">백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/embed/#?secret=AeoFCex2O2#?secret=Baal9ouENg" data-secret="Baal9ouENg" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<figure class="wp-block-image size-full"><img decoding="async" width="1465" height="1101" src="https://lycos7560.com/wp-content/uploads/2023/02/image-64.png" alt="" class="wp-image-33098" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-64.png 1465w, https://lycos7560.com/wp-content/uploads/2023/02/image-64-300x225.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-64-768x577.png 768w" sizes="(max-width: 1465px) 100vw, 1465px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">코드 C++</h3>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;vector>

using namespace std;

constexpr long long int INF = INT64_MAX;

constexpr int MAXN = 501;

long long int disArr[MAXN];

bool check = false; // 음의 순환이 있는지 확인

// N : 도시의 개수, M : 버스 노선의 개수
// A : 시작 도시, B : 도착 도시, C : 걸리는 시간
int N, M, A, B, C;

vector&lt;pair&lt;int, int>> graph[MAXN];

int main()
{
	ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
	// cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
	cin.tie(NULL);
	std::cout.tie(NULL);

	cin >> N >> M;

	for (int i = 0; i &lt; M; i++) {
		cin >> A >> B >> C;
		// 단방향
		graph[A].push_back(make_pair(B, C));
	}

	// 배열 초기화
	fill(disArr, disArr + MAXN, INF);

	disArr[1] = 0;


	for (int k = 1; k &lt;= N; k++) {// (모든 정점의 수 - 1) 번 확인한다.
		// 모든 노선을 확인한다.
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 0; j &lt; graph[i].size(); j++) {

				int u = i; // 시작점
				int v = graph[i][j].first; // 도착점
				int weight = graph[i][j].second; // 가중치

				// 만약 임시 배열이 무한대가 아니고 &amp;&amp;
				// 시작 임시 배열의 가중치가 도착지의 가중치보다 작다면
				if (disArr[u] != INF &amp;&amp; disArr[u] + weight &lt; disArr[v]) {

					disArr[v] = disArr[u] + weight; // 임시배열을 업데이트 해준다.

					// K가 N-1일때 모든 정점을 확인한 후
					// K가 N일때 업데이트가 있다면 음의 순환이 있다는 이야기
					if (k == N) { 
						cout &lt;&lt; "-1";
						return 0;
					}
				}
			}
		}
	}

	for (int i = 2; i &lt;= N; i++) {
		if (disArr[i] == INF) cout &lt;&lt; "-1" &lt;&lt; "\n";
		else cout &lt;&lt; disArr[i] &lt;&lt; "\n";
	}

	return 0;
}</pre>



<div style="height:150px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Dijkstra 알고리즘 vs Bellman–Ford 알고리즘 </h2>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">1. 가중치의 차이</h3>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-embed is-type-wp-embed is-provider-어제와-내일의-나-그-사이의-이야기 wp-block-embed-어제와-내일의-나-그-사이의-이야기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="OjdsQtMLPm"><a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%8b%a4%ec%9d%b5%ec%8a%a4%ed%8a%b8%eb%9d%bc-%eb%8d%b0%ec%9d%b4%ed%81%ac%ec%8a%a4%ed%8a%b8%eb%9d%bcdijkstra/5223/">알고리즘 &#8211; 다익스트라/데이크스트라(Dijkstra) 알고리즘 정리</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;알고리즘 &#8211; 다익스트라/데이크스트라(Dijkstra) 알고리즘 정리&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%8b%a4%ec%9d%b5%ec%8a%a4%ed%8a%b8%eb%9d%bc-%eb%8d%b0%ec%9d%b4%ed%81%ac%ec%8a%a4%ed%8a%b8%eb%9d%bcdijkstra/5223/embed/#?secret=64mzTRITI9#?secret=OjdsQtMLPm" data-secret="OjdsQtMLPm" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">예전에 정리한 Dijkstra 도 Bellman–Ford 와 같은 최단 경로 알고리즘입니다.</p>



<p class="has-medium-font-size wp-block-paragraph">하지만 Dijkstra 알고리즘은 <strong>가중치가 양수일 때만 사용 가능하다는 중요한 특징</strong>을 가지고 있습니다.</p>



<p class="has-medium-font-size wp-block-paragraph">따라서 가중치가 전부 양수라면 Dijkstra 알고리즘을 사용하고 </p>



<p class="has-medium-font-size wp-block-paragraph">하나라도 음수의 가중치가 있다면 </p>



<p class="has-medium-font-size wp-block-paragraph">Bellman–Ford 알고리즘을 사용해야 합니다.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">위 : Dijkstra / 아래 Bellman–Ford (.gif)</p>



<figure class="wp-block-image size-full"><img decoding="async" width="560" height="600" src="https://lycos7560.com/wp-content/uploads/2023/02/560px-Shortest_path_Dijkstra_vs_BellmanFord.gif" alt="" class="wp-image-33052"/><figcaption class="wp-element-caption"><a href="https://commons.wikimedia.org/wiki/File:Shortest_path_Dijkstra_vs_BellmanFord.gif" target="_blank" rel="noreferrer noopener">https://commons.wikimedia.org/wiki/File:Shortest_path_Dijkstra_vs_BellmanFord.gif</a></figcaption></figure>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">2. 시간 복잡도의 차이</h3>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">V는 꼭짓점의 수이고 E는 간선의 개수라고 한다면</p>



<p class="has-medium-font-size wp-block-paragraph">Dijkstra 알고리즘은 O(E*logV)의 시간 복잡도를 가지고</p>



<p class="has-medium-font-size wp-block-paragraph">Bellman-Ford 알고리즘은 O(V*E)의 시간 복잡도를 가집니다.</p>



<p class="has-medium-font-size wp-block-paragraph">따라서 음의 가중치가 없다면 Bellman-Ford 알고리즘보다는 </p>



<p class="has-medium-font-size wp-block-paragraph">Dijkstra 알고리즘을 이용하여 해결하는 것이 더 좋은 방법입니다.</p>



<p class="has-medium-font-size wp-block-paragraph">(Dijkstra 알고리즘은 우선순위 대기열을 사용하여 처리해야 하는 정점을 유지하는 반면, </p>



<p class="has-medium-font-size wp-block-paragraph">Bellman-Ford 알고리즘은 가장 짧은 경로를 찾기 위해 모든 정점에 대해 반복합니다.)</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



			<div class="wp-block-uagb-post-carousel uagb-post-grid  uagb-post__image-position-top uagb-post__image-enabled uagb-block-37106eb0     uagb-post__arrow-outside uagb-post__items uagb-post__columns-5 is-carousel uagb-post__columns-tablet-2 uagb-post__columns-mobile-1" data-total="1" style="">

												<article class="uagb-post__inner-wrap">								<div class='uagb-post__image'>
									<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/" target="_self" rel="bookmark noopener noreferrer"><img decoding="async" width="1920" height="1003" src="https://lycos7560.com/wp-content/uploads/boj-og.png" class="attachment-large size-large" alt="" srcset="https://lycos7560.com/wp-content/uploads/boj-og.png 1920w, https://lycos7560.com/wp-content/uploads/boj-og-300x157.png 300w, https://lycos7560.com/wp-content/uploads/boj-og-768x401.png 768w, https://lycos7560.com/wp-content/uploads/boj-og-1536x802.png 1536w, https://lycos7560.com/wp-content/uploads/boj-og-2048x1070.png 2048w" sizes="(max-width: 1920px) 100vw, 1920px" />					</a>
									</div>
						<h4 class="uagb-post__title uagb-post__text">
				<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/" target="_self" rel="bookmark noopener noreferrer">백준 1865번 (웜홀, C++, Bellman–Ford) [BAEKJOON]</a>
			</h4>
						<div class='uagb-post__text uagb-post-grid-byline'>
							</div>
						<div class="uagb-post__text uagb-post__cta wp-block-button">
				<a class="wp-block-button__link uagb-text-link" style="" href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1865%eb%b2%88-%ec%9b%9c%ed%99%80-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33135/" target="_self" rel="bookmark noopener noreferrer">더 읽기</a>
			</div>
			
									</article>
																<article class="uagb-post__inner-wrap">								<div class='uagb-post__image'>
									<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/" target="_self" rel="bookmark noopener noreferrer"><img decoding="async" width="1024" height="535" src="https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1-1024x535.png" class="attachment-large size-large" alt="" srcset="https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1-1024x535.png 1024w, https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1-300x157.png 300w, https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1-768x401.png 768w, https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1-1536x803.png 1536w, https://lycos7560.com/wp-content/uploads/2022/10/boj-og-1-2048x1070-1.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" />					</a>
									</div>
						<h4 class="uagb-post__title uagb-post__text">
				<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/" target="_self" rel="bookmark noopener noreferrer">백준 1738번 (골목길, C++, Bellman–Ford) / 추가 반례 [BAEKJOON]</a>
			</h4>
						<div class='uagb-post__text uagb-post-grid-byline'>
							</div>
						<div class="uagb-post__text uagb-post__cta wp-block-button">
				<a class="wp-block-button__link uagb-text-link" style="" href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1738%eb%b2%88-%ea%b3%a8%eb%aa%a9%ea%b8%b8-c-bellman-ford-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/33119/" target="_self" rel="bookmark noopener noreferrer">더 읽기</a>
			</div>
			
									</article>
																<article class="uagb-post__inner-wrap">								<div class='uagb-post__image'>
									<a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/" target="_self" rel="bookmark noopener noreferrer"><img decoding="async" width="1024" height="640" src="https://lycos7560.com/wp-content/uploads/algorithm-wallpaper.jpg" class="attachment-large size-large" alt="" srcset="https://lycos7560.com/wp-content/uploads/algorithm-wallpaper.jpg 1024w, https://lycos7560.com/wp-content/uploads/algorithm-wallpaper-300x188.jpg 300w, https://lycos7560.com/wp-content/uploads/algorithm-wallpaper-768x480.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" />					</a>
									</div>
						<h4 class="uagb-post__title uagb-post__text">
				<a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/" target="_self" rel="bookmark noopener noreferrer">알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</a>
			</h4>
						<div class='uagb-post__text uagb-post-grid-byline'>
							</div>
						<div class="uagb-post__text uagb-post__cta wp-block-button">
				<a class="wp-block-button__link uagb-text-link" style="" href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/" target="_self" rel="bookmark noopener noreferrer">더 읽기</a>
			</div>
			
									</article>
																<article class="uagb-post__inner-wrap">								<div class='uagb-post__image'>
									<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/" target="_self" rel="bookmark noopener noreferrer"><img decoding="async" width="1920" height="1003" src="https://lycos7560.com/wp-content/uploads/boj-og-1.png" class="attachment-large size-large" alt="" srcset="https://lycos7560.com/wp-content/uploads/boj-og-1.png 1920w, https://lycos7560.com/wp-content/uploads/boj-og-1-300x157.png 300w, https://lycos7560.com/wp-content/uploads/boj-og-1-768x401.png 768w, https://lycos7560.com/wp-content/uploads/boj-og-1-1536x802.png 1536w, https://lycos7560.com/wp-content/uploads/boj-og-1-2048x1070.png 2048w" sizes="(max-width: 1920px) 100vw, 1920px" />					</a>
									</div>
						<h4 class="uagb-post__title uagb-post__text">
				<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/" target="_self" rel="bookmark noopener noreferrer">백준 1219번 (오민식의 고민, C++, Bellman–Ford) [BAEKJOON]</a>
			</h4>
						<div class='uagb-post__text uagb-post-grid-byline'>
							</div>
						<div class="uagb-post__text uagb-post__cta wp-block-button">
				<a class="wp-block-button__link uagb-text-link" style="" href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1219%eb%b2%88-%ec%98%a4%eb%af%bc%ec%8b%9d%ec%9d%98-%ea%b3%a0%eb%af%bc-c-bellman-ford-baekjoon/33149/" target="_self" rel="bookmark noopener noreferrer">더 읽기</a>
			</div>
			
									</article>
																<article class="uagb-post__inner-wrap">								<div class='uagb-post__image'>
									<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/" target="_self" rel="bookmark noopener noreferrer"><img decoding="async" width="1920" height="1003" src="https://lycos7560.com/wp-content/uploads/boj-og.png" class="attachment-large size-large" alt="" srcset="https://lycos7560.com/wp-content/uploads/boj-og.png 1920w, https://lycos7560.com/wp-content/uploads/boj-og-300x157.png 300w, https://lycos7560.com/wp-content/uploads/boj-og-768x401.png 768w, https://lycos7560.com/wp-content/uploads/boj-og-1536x802.png 1536w, https://lycos7560.com/wp-content/uploads/boj-og-2048x1070.png 2048w" sizes="(max-width: 1920px) 100vw, 1920px" />					</a>
									</div>
						<h4 class="uagb-post__title uagb-post__text">
				<a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/" target="_self" rel="bookmark noopener noreferrer">백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]</a>
			</h4>
						<div class='uagb-post__text uagb-post-grid-byline'>
							</div>
						<div class="uagb-post__text uagb-post__cta wp-block-button">
				<a class="wp-block-button__link uagb-text-link" style="" href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/" target="_self" rel="bookmark noopener noreferrer">더 읽기</a>
			</div>
			
									</article>
											</div>
			


<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problemset?sort=ac_desc&amp;algo=10" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problemset?sort=ac_desc&amp;algo=10</a> &lt;- 백준 Bellman-Ford 알고리즘 문제</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/">알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/#comments</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 10 Feb 2023 17:54:24 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[11657]]></category>
		<category><![CDATA[11657번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Bellman–Ford]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[그래프 이론]]></category>
		<category><![CDATA[그래프 탐색]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[길찾기]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 11657]]></category>
		<category><![CDATA[백준 11657번]]></category>
		<category><![CDATA[벨만-포드]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[타임머신]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33077</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 11657번 '타임머신' 문제에 대한 글입니다.  Bellman–Ford 알고리즘을 적용하여 문제를 해결하였습니다. (This is an article about the 'Time Machine' problem in BAEKJOON No. 11657. We solved the problem by applying Bellman–Ford algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/">백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>


				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-96198611      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차 테이블						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#타임머신" class="uagb-toc-link__trigger">타임머신</a><li class="uagb-toc__list"><a href="#풀이-과정" class="uagb-toc-link__trigger">풀이 과정</a><li class="uagb-toc__list"><a href="#통과된-코드" class="uagb-toc-link__trigger">통과된 코드</a></ol>					</div>
									</div>
				</div>
			


<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">타임머신</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/11657" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/11657</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure id="problem-info" class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">시간 제한</th><th class="has-text-align-left" data-align="left">메모리 제한</th><th class="has-text-align-left" data-align="left">제출</th><th class="has-text-align-left" data-align="left">정답</th><th class="has-text-align-left" data-align="left">맞힌 사람</th><th class="has-text-align-left" data-align="left">정답 비율</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">1 초</td><td class="has-text-align-left" data-align="left">256 MB</td><td class="has-text-align-left" data-align="left">48876</td><td class="has-text-align-left" data-align="left">10037</td><td class="has-text-align-left" data-align="left">6258</td><td class="has-text-align-left" data-align="left">22.768%</td></tr></tbody></table></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">문제</h2>



<p class="has-medium-font-size wp-block-paragraph">N개의 도시가 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">그리고 한 도시에서 출발하여 다른 도시에 도착하는&nbsp;버스가 M개 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">각 버스는 A, B, C로 나타낼 수 있는데, A는 시작도시, B는 도착도시, C는 버스를 타고 이동하는데 걸리는 시간이다.</p>



<p class="has-medium-font-size wp-block-paragraph">시간 C가 양수가 아닌 경우가 있다.</p>



<p class="has-medium-font-size wp-block-paragraph">C = 0인 경우는 순간 이동을 하는 경우, C &lt; 0인 경우는 타임머신으로 시간을 되돌아가는 경우이다.</p>



<p class="has-medium-font-size wp-block-paragraph">1번 도시에서 출발해서 나머지 도시로 가는 가장 빠른 시간을 구하는 프로그램을 작성하시오.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 도시의 개수 N (1 ≤ N ≤ 500), 버스 노선의 개수 M (1 ≤ M ≤ 6,000)이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">둘째 줄부터 M개의 줄에는 버스 노선의 정보 A, B, C&nbsp;(1 ≤ A, B ≤ N,&nbsp;-10,000 ≤ C ≤ 10,000)가 주어진다.&nbsp;</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">만약 1번 도시에서 출발해 어떤 도시로 가는 과정에서 시간을 무한히 오래 전으로 되돌릴 수 있다면 첫째 줄에 -1을 출력한다. </p>



<p class="has-medium-font-size wp-block-paragraph">그렇지 않다면 N-1개 줄에 걸쳐 각 줄에 1번 도시에서 출발해 2번 도시, 3번 도시, &#8230;, N번 도시로 가는 가장 빠른 시간을 순서대로 출력한다. </p>



<p class="has-medium-font-size wp-block-paragraph">만약 해당 도시로 가는 경로가 없다면 대신 -1을 출력한다.</p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3 4
1 2 4
1 3 3
2 3 -1
3 1 -2</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4
3</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3 4
1 2 4
1 3 3
2 3 -4
3 1 -2</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3 2
1 2 4
1 2 3</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3
-1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출처</h2>



<ul class="wp-block-list">
<li>어색한 표현을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/alex9801" target="_blank" rel="noreferrer noopener">alex9801</a>,&nbsp;<a href="https://www.acmicpc.net/user/myungwoo" target="_blank" rel="noreferrer noopener">myungwoo</a>,&nbsp;<a href="https://www.acmicpc.net/user/rim">rim</a></li>



<li>문제를 만든 사람:&nbsp;<a href="https://www.acmicpc.net/user/baekjoon" target="_blank" rel="noreferrer noopener">baekjoon</a></li>



<li>데이터를 추가한 사람:&nbsp;<a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a>,&nbsp;<a href="https://www.acmicpc.net/user/doju" target="_blank" rel="noreferrer noopener">doju</a>,&nbsp;<a href="https://www.acmicpc.net/user/ganghe74" target="_blank" rel="noreferrer noopener">ganghe74</a></li>
</ul>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">알고리즘 분류</h2>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/10" target="_blank" rel="noreferrer noopener">벨만–포드</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<figure class="wp-block-embed is-type-wp-embed is-provider-어제와-내일의-나-그-사이의-이야기 wp-block-embed-어제와-내일의-나-그-사이의-이야기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="0s1toz8l52"><a href="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/">알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;알고리즘 &#8211; 벨만-포드 (Bellman–Ford Algorithm) 알고리즘 정리&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/etc/%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%eb%b2%a8%eb%a7%8c-%ed%8f%ac%eb%93%9c-bellman-ford-algorithm-%ec%95%8c%ea%b3%a0%eb%a6%ac%ec%a6%98-%ec%a0%95%eb%a6%ac/33044/embed/#?secret=D9cKdZzqwa#?secret=0s1toz8l52" data-secret="0s1toz8l52" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">풀이 과정</h1>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1502" height="1920" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_024303329.jpg" alt="" class="wp-image-33089" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_024303329.jpg 1502w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_024303329-235x300.jpg 235w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_024303329-768x982.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230211_024303329-1202x1536.jpg 1202w" sizes="(max-width: 1502px) 100vw, 1502px" /></figure>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">통과된 코드</h1>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;vector>

using namespace std;

constexpr long long int INF = INT64_MAX;

constexpr int MAXN = 501;

long long int disArr[MAXN];

bool check = false; // 음의 순환이 있는지 확인

// N : 도시의 개수, M : 버스 노선의 개수
// A : 시작 도시, B : 도착 도시, C : 걸리는 시간
int N, M, A, B, C;

vector&lt;pair&lt;int, int>> graph[MAXN];

int main()
{
	ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
	// cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
	cin.tie(NULL);
	std::cout.tie(NULL);

	cin >> N >> M;

	for (int i = 0; i &lt; M; i++) {
		cin >> A >> B >> C;
		// 단방향
		graph[A].push_back(make_pair(B, C));
	}

	// 배열 초기화
	fill(disArr, disArr + MAXN, INF);

	disArr[1] = 0;


	for (int k = 1; k &lt;= N; k++) {// (모든 정점의 수 - 1) 번 확인한다.
		// 모든 노선을 확인한다.
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 0; j &lt; graph[i].size(); j++) {

				int u = i; // 시작점
				int v = graph[i][j].first; // 도착점
				int weight = graph[i][j].second; // 가중치

				// 만약 임시 배열이 무한대가 아니고 &amp;&amp;
				// 시작 임시 배열의 가중치가 도착지의 가중치보다 작다면
				if (disArr[u] != INF &amp;&amp; disArr[u] + weight &lt; disArr[v]) {

					disArr[v] = disArr[u] + weight; // 임시배열을 업데이트 해준다.

					// K가 N-1일때 모든 정점을 확인한 후
					// K가 N일때 업데이트가 있다면 음의 순환이 있다는 이야기
					if (k == N) { 
						cout &lt;&lt; "-1";
						return 0;
					}
				}
			}
		}
	}

	for (int i = 2; i &lt;= N; i++) {
		if (disArr[i] == INF) cout &lt;&lt; "-1" &lt;&lt; "\n";
		else cout &lt;&lt; disArr[i] &lt;&lt; "\n";
	}

	return 0;
}</pre>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1041" height="187" src="https://lycos7560.com/wp-content/uploads/2023/02/image-62.png" alt="" class="wp-image-33086" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-62.png 1041w, https://lycos7560.com/wp-content/uploads/2023/02/image-62-300x54.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-62-768x138.png 768w" sizes="(max-width: 1041px) 100vw, 1041px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/">백준 11657번 (타임머신, C++, Bellman–Ford) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11657%eb%b2%88-%ed%83%80%ec%9e%84%eb%a8%b8%ec%8b%a0-c-bellman-ford-baekjoon/33077/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
