<?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>길찾기 Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<atom:link href="https://lycos7560.com/tag/%EA%B8%B8%EC%B0%BE%EA%B8%B0/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>생각의 흐름을 타고 다니며 만드는 블로그</description>
	<lastBuildDate>Wed, 15 Oct 2025 05:32:31 +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>길찾기 Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>백준 1613번 (역사, C++, Floyd-Warshall) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1613%eb%b2%88-%ec%97%ad%ec%82%ac-c-floyd-warshall-baekjoon/33239/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1613%eb%b2%88-%ec%97%ad%ec%82%ac-c-floyd-warshall-baekjoon/33239/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sat, 18 Feb 2023 01:44:41 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1613]]></category>
		<category><![CDATA[1613번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Floyd-Warshall]]></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[백준 1613]]></category>
		<category><![CDATA[백준 1613번]]></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=33239</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 1613번 '역사' 문제에 대한 글입니다. Floyd-Warshall 알고리즘을 이용하여 해결하였습니다. (This is BAEKJOON's 1613 'History' issue. It was solved using the Floyd-Warshall algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1613%eb%b2%88-%ec%97%ad%ec%82%ac-c-floyd-warshall-baekjoon/33239/">백준 1613번 (역사, C++, Floyd-Warshall) [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-6b88ed7e      "
					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/1613" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1613</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">128 MB</td><td class="has-text-align-left" data-align="left">13395</td><td class="has-text-align-left" data-align="left">4248</td><td class="has-text-align-left" data-align="left">3117</td><td class="has-text-align-left" data-align="left">34.196%</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">이를 해결하는 프로그램을 작성해 보도록 하자.</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(400 이하의 자연수)과 알고 있는 사건의 전후 관계의 개수 k(50,000 이하의 자연수)가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">다음 k줄에는 전후 관계를 알고 있는 두 사건의 번호가 주어진다. </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">다음에는 사건의 전후 관계를 알고 싶은 사건 쌍의 수 s(50,000 이하의 자연수)이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">다음 s줄에는 각각 서로 다른 두 사건의 번호가 주어진다. </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">s줄에 걸쳐 물음에 답한다. </p>



<p class="has-medium-font-size wp-block-paragraph">각 줄에 만일 앞에 있는 번호의 사건이 먼저 일어났으면 -1, </p>



<p class="has-medium-font-size wp-block-paragraph">뒤에 있는 번호의 사건이 먼저 일어났으면 1, 어떤지 모르면(유추할 수 없으면) 0을 출력한다.</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 5
1 2
1 3
2 3
3 4
2 4
3
1 5
2 4
3 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="">0
-1
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/author5" target="_blank" rel="noreferrer noopener">author5</a></li>



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



<li>문제의 오타를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/joonas" target="_blank" rel="noreferrer noopener">joonas</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/31" 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 fetchpriority="high" decoding="async" width="1600" height="1306" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230218_104211238.jpg" alt="" class="wp-image-33244" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230218_104211238.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230218_104211238-300x245.jpg 300w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230218_104211238-768x627.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230218_104211238-1536x1254.jpg 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></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>
#include &lt;list>

using namespace std;

int n, k, f, b, s;

constexpr int MAX = 401;

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

list&lt;pair&lt;int, int>> myList;

int disArr[MAX][MAX];

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

	cin >> n >> k;

	// 사건의 전후 관계 입력
	for (int i = 0; i &lt; k; i++) {
		cin >> f >> b;
		graph[f].push_back(make_pair(b, -1));
		graph[b].push_back(make_pair(f, 1)); // 역방향 가능
	}

	// 질문을 입력 받는다.
	cin >> s;

	pair&lt;int, int> tempP;

	while (s--) { // 문제를 입력받는다.
		cin >> tempP.first >> tempP.second;
		myList.push_back(tempP);
	}

	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;
			disArr[i][v] = weight;
		}
	}


	for (int k = 1; k &lt;= n; k++) {
		for (int i = 1; i &lt;= n; i++) {
			for (int j = 1; j &lt;= n; j++) {
				if (i == j) disArr[i][j] = 0;
				else if (disArr[i][k] == 1 &amp;&amp; disArr[k][j] == 1) disArr[i][j] = 1;
				else if (disArr[i][k] == -1 &amp;&amp; disArr[k][j] == -1) disArr[i][j] = -1;
			}
		}
	}

	for (auto it = myList.begin(); it != myList.end(); it++) {
		cout &lt;&lt; disArr[it->first][it->second] &lt;&lt; "\n";

	}

	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="912" height="126" src="https://lycos7560.com/wp-content/uploads/2023/02/image-83.png" alt="" class="wp-image-33242" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-83.png 912w, https://lycos7560.com/wp-content/uploads/2023/02/image-83-300x41.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-83-768x106.png 768w" sizes="(max-width: 912px) 100vw, 912px" /></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-1613%eb%b2%88-%ec%97%ad%ec%82%ac-c-floyd-warshall-baekjoon/33239/">백준 1613번 (역사, C++, Floyd-Warshall) [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-1613%eb%b2%88-%ec%97%ad%ec%82%ac-c-floyd-warshall-baekjoon/33239/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 1507번 (궁금한 민호, C++, Floyd-Warshall) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1507%eb%b2%88-%ea%b6%81%ea%b8%88%ed%95%9c-%eb%af%bc%ed%98%b8-c-floyd-warshall-baekjoon/33230/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1507%eb%b2%88-%ea%b6%81%ea%b8%88%ed%95%9c-%eb%af%bc%ed%98%b8-c-floyd-warshall-baekjoon/33230/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 17 Feb 2023 07:43:51 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1507]]></category>
		<category><![CDATA[1507번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Floyd-Warshall]]></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[백준 1507]]></category>
		<category><![CDATA[백준 1507번]]></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=33230</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 1507번 '궁금한 민호' 문제에 대한 글입니다. 'Floyd-Warshall' 알고리즘을 이용하여 해결하였습니다.  (This is BAEKJOON's 1507 "Curious Minho" question. Solved using the 'Floyd-Warshall' algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-1507%eb%b2%88-%ea%b6%81%ea%b8%88%ed%95%9c-%eb%af%bc%ed%98%b8-c-floyd-warshall-baekjoon/33230/">백준 1507번 (궁금한 민호, C++, Floyd-Warshall) [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-54dab500      "
					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/1507" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1507</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">5291</td><td class="has-text-align-left" data-align="left">2771</td><td class="has-text-align-left" data-align="left">2180</td><td class="has-text-align-left" data-align="left">51.198%</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">각 도시는 M개의 도로로 연결되어 있으며, 각 도로를 지날 때 필요한 시간이 존재한다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">도로는 잘 연결되어 있기 때문에, 도시 A에서 B로 이동할 수 없는 경우는 존재하지 않는다.</p>



<p class="has-medium-font-size wp-block-paragraph">도시 A에서 도시 B로 바로 갈 수 있는 도로가 있거나, </p>



<p class="has-medium-font-size wp-block-paragraph">다른 도시를 거쳐서 갈 수 있을 때, 도시 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">예를 들어, 도시 1-2, 2-3, 1-4, 3-4, 4-5, 3-5를 연결하는 도로만 있다고 가정해도, 강호가 구한 모든 쌍의 최솟값을 구할 수 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">이 경우 도로의&nbsp;개수는 6개이고, 모든 도로의 시간의 합은 55이다.</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(1 ≤ N ≤ 20)이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">둘째 줄부터 N개의 줄에 각각의 도시 사이에 이동하는데 필요한 시간이&nbsp;주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">A에서 B로 가는 시간과 B에서 A로 가는 시간은 같다. 또, A와 B가 같은 경우에는&nbsp;0이 주어지고, </p>



<p class="has-medium-font-size wp-block-paragraph">그 외의 경우에 필요한 시간은 2500보다 작거나 같은 자연수이다.</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;최소일 때, 모든 도로의 시간의 합을 출력한다. </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="">5
0 6 15 2 6
6 0 9 8 12
15 9 0 16 18
2 8 16 0 4
6 12 18 4 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="">55</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
0 2 2
2 0 2
2 2 0</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="">6</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="">8
0 1 6 17 26 13 7 16
1 0 5 16 25 12 7 15
6 5 0 21 21 8 12 11
17 16 21 0 41 28 23 31
26 25 21 41 0 13 32 10
13 12 8 28 13 0 19 3
7 7 12 23 32 19 0 22
16 15 11 31 10 3 22 0</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="">69</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="">3
0 1 3
1 0 1
3 1 0</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="">-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/baekjoon" target="_blank" rel="noreferrer noopener">baekjoon</a></li>



<li>빠진 조건을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/medic_programmer" target="_blank" rel="noreferrer noopener">medic_programmer</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/31" 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>



<p class="has-medium-font-size wp-block-paragraph">i -&gt; j로 가는 최단경로와 i -&gt; k, k -&gt; j 로 가는 최단경로의 합이 같다면 i -&gt; j경로는 없애준다.</p>



<p class="has-medium-font-size wp-block-paragraph">i -&gt; j의 최단경로가 더 크다면 입력이 잘못된 것이므로 result를 -1로 저장해준다.</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="1600" height="1343" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_163646475.jpg" alt="" class="wp-image-33235" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_163646475.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_163646475-300x252.jpg 300w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_163646475-768x645.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_163646475-1536x1289.jpg 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></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>

using namespace std;

constexpr int MAX = 21;

int disArr[MAX][MAX];

int route[MAX][MAX];

int N, result;

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

	cin >> N;

	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {
			cin >> disArr[i][j];
			route[i][j] = disArr[i][j];
		}
	}

	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {
			for (int k = 1; k &lt;= N; k++) {

				if (j == k || i == k) continue;

				// 불가능한 경우이므로 -1 출력
				if (disArr[i][j] > disArr[i][k] + disArr[k][j]) {
					cout &lt;&lt; "-1";
					return 0;
				}

				// 경로를 지워준다.
				if (disArr[i][j] == disArr[i][k] + disArr[k][j]) route[i][j] = 0;
			}
		}
	}


	for (int i = 1; i &lt;= N; i++) 
		for (int j = 1; j &lt;= N; j++) result += route[i][j];
	
	// 반으로 나누어준다.
	cout &lt;&lt; result / 2;

	return 0;
}</pre>



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



<figure class="wp-block-image size-full is-resized"><img decoding="async" src="https://lycos7560.com/wp-content/uploads/2023/02/image-82.png" alt="" class="wp-image-33232" width="1151" height="112" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-82.png 909w, https://lycos7560.com/wp-content/uploads/2023/02/image-82-300x29.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-82-768x75.png 768w" sizes="(max-width: 1151px) 100vw, 1151px" /></figure>



<div style="height:50px" 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-1507%eb%b2%88-%ea%b6%81%ea%b8%88%ed%95%9c-%eb%af%bc%ed%98%b8-c-floyd-warshall-baekjoon/33230/">백준 1507번 (궁금한 민호, C++, Floyd-Warshall) [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-1507%eb%b2%88-%ea%b6%81%ea%b8%88%ed%95%9c-%eb%af%bc%ed%98%b8-c-floyd-warshall-baekjoon/33230/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 11562번 (백양로 브레이크, C++, Floyd-Warshall) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11562%eb%b2%88-%eb%b0%b1%ec%96%91%eb%a1%9c-%eb%b8%8c%eb%a0%88%ec%9d%b4%ed%81%ac-c-floyd-warshall-baekjoon/33218/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11562%eb%b2%88-%eb%b0%b1%ec%96%91%eb%a1%9c-%eb%b8%8c%eb%a0%88%ec%9d%b4%ed%81%ac-c-floyd-warshall-baekjoon/33218/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 17 Feb 2023 04:38:02 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[11562]]></category>
		<category><![CDATA[11562번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Floyd-Warshall]]></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[백준 11562]]></category>
		<category><![CDATA[백준 11562번]]></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=33218</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 11562번 '백양로 브레이크' 문제에 대한 글입니다. 'Floyd-Warshall' 알고리즘을 이용하여 해결하였습니다. (This is an article on the issue of Baekyang-ro Brake, BAEKJOON No. 11562. Solved using the 'Floyd-Warshall' algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11562%eb%b2%88-%eb%b0%b1%ec%96%91%eb%a1%9c-%eb%b8%8c%eb%a0%88%ec%9d%b4%ed%81%ac-c-floyd-warshall-baekjoon/33218/">백준 11562번 (백양로 브레이크, C++, Floyd-Warshall) [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-9a3904cd      "
					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="#시간-초과-코드-dfs" class="uagb-toc-link__trigger">시간 초과 코드 (DFS)</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/11562" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/11562</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">2698</td><td class="has-text-align-left" data-align="left">1354</td><td class="has-text-align-left" data-align="left">1024</td><td class="has-text-align-left" data-align="left">47.828%</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">서울 소재 Y모 대학교에서 대규모 공사를 진행하면서, 학교가 마치 미로처럼 변해버리고 말았다. </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">길을 잃어 3일 밤낮을 헤매다가 공학관에서 종합관으로 가는 길은 존재하지 않는다는 결론을 내렸다.</p>



<p class="has-medium-font-size wp-block-paragraph">3일 사이에 과제도 내지 못하고 출석도 하지 못해 학사경고 위기에 처한 남규는 전공을 살려 </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">&#8220;공학관에서 대강당 갈 수 있어?&#8221;</p>



<p class="has-medium-font-size wp-block-paragraph">&#8220;상경대 별관에서 학관으로는?&#8221;</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">첫 줄에 Y대학교 건물의 수 n과 길의 수 m이 주어진다. (n ≤ 250, m ≤ n * (n &#8211; 1) / 2 )</p>



<p class="has-medium-font-size wp-block-paragraph">다음 m줄에 걸쳐, u v b (1 ≤ u ≤ n, 1 ≤ v ≤ n, u != v, b = 0 또는 1) 의 형태로 길에 대한 정보가 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">b가 0일 경우 u에서 v로 가는 일방통행 길인 것이고, b가 1일 경우 u와 v를 잇는 양방향 길이다.</p>



<p class="has-medium-font-size wp-block-paragraph">어떤 두 건물 사이를 잇는 길은 최대 한 개이다.</p>



<p class="has-medium-font-size wp-block-paragraph">다음 줄에 학생들의 질문의 수 k가 주어진다. (1 ≤ k ≤ 30,000)</p>



<p class="has-medium-font-size wp-block-paragraph">다음 k줄에 걸쳐 s e (1 ≤ s ≤ n, 1 ≤ e ≤ n)의 형태로 학생들의 질문들이 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">이는 질문한 학생이 건물 s에서 건물 e로 가고 싶다는 의미이다.</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">출력은 k줄에 걸쳐 이루어진다.</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">예제 입력 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
1 2 0
2 3 1
3 4 0
7
1 1
1 2
2 1
1 4
4 1
2 3
4 3</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="">0
0
1
0
2
0
1</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/5" target="_blank" rel="noreferrer noopener">University</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/334" target="_blank" rel="noreferrer noopener">연세대학교</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/1419" target="_blank" rel="noreferrer noopener">2015 연세대학교 프로그래밍 경시대회</a>&nbsp;F번</p>



<ul class="wp-block-list">
<li>문제를 만든 사람:&nbsp;<a href="https://www.acmicpc.net/user/portableangel" target="_blank" rel="noreferrer noopener">portableangel</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/31" 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="1600" height="1826" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_133534115.jpg" alt="" class="wp-image-33225" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_133534115.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_133534115-263x300.jpg 263w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_133534115-768x876.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_133534115-1346x1536.jpg 1346w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



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



<h1 class="wp-block-heading">시간 초과 코드 (DFS)</h1>



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



<p class="has-medium-font-size wp-block-paragraph">DFS 탐색을 이용하여 도착지부터 출발지까지 최소 거리를 카운트하여 탐색한 코드 </p>



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



<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>
#include &lt;list>

using namespace std;

constexpr int INF = INT32_MAX / 2;

constexpr int MAX = 251;

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

list&lt;pair&lt;int, int>> myList;

int disArr[MAX][MAX];
bool check[MAX];

// N : 도시의 수, M : 길의 수
int N, M, s, d, w, b, K, result;

void Tracking(int start, int now, int cnt)
{
	if (start == now || disArr[now][start] == 0) {
		result = min(result, cnt);
		return;
	}

	for (int j = 0; j &lt; graph[now].size(); j++) {
		int v = graph[now][j].first; // 도착점
		int weight = graph[now][j].second; // 가중치

		if (check[v] == true) continue;

		if (weight == INF) {
			cnt++;
			check[v] = true;
			Tracking(start, v, cnt);
			check[v] = false;
			cnt--;	
		}
		else
		{
			check[v] = true;
			Tracking(start, v, cnt);
			check[v] = false;
		}
	}
}


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

	cin >> N >> M;

	// 길의 정보를 입력
	for (int i = 0; i &lt; M; i++) {

		// 출발 s, 도착 d, b 양/단 방향
		cin >> s >> d >> b;

		if (b == 0) { // 단방향
			graph[s].push_back(make_pair(d, 0));
			graph[d].push_back(make_pair(s, INF));
		}
		else { // 양방향
			graph[s].push_back(make_pair(d, 0));
			graph[d].push_back(make_pair(s, 0));
		}

	}

	// 질문을 입력 받는다.
	cin >> K;
	pair&lt;int, int> tempP;
	while (K--) {
		cin >> tempP.first >> tempP.second;
		myList.push_back(tempP);
	}




	// 최단 거리 배열 disArr 배열을 INF 초기화
	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {

			if (i == j) disArr[i][j] = 0;
			else disArr[i][j] = INF;

		}
	}

	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][v] > weight) 	disArr[i][v] = weight;

		}
	}

	// 무지성 플로이드
	for (int k = 1; k &lt;= N; k++) {
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 1; j &lt;= N; j++) {

				if (i == j) disArr[i][j] = 0;
				else disArr[i][j] = min(disArr[i][j], disArr[i][k] + disArr[k][j]);

			}
		}
	}

	for (auto it = myList.begin(); it != myList.end(); it++) {
		result = INF;
		if (disArr[it->first][it->second] == 0) cout &lt;&lt; disArr[it->first][it->second] &lt;&lt; "\n";
		else {
			Tracking(it->second, it->first, 0);
			cout &lt;&lt; result &lt;&lt; "\n";
		}
	}

	return 0;
}</pre>



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



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



<p class="has-medium-font-size wp-block-paragraph">Floyd-Warshall 알고리즘이 어떤 식으로 작동하는지 안다면 뒤집는 부분에 왜 1 이 들어가는지 알 수 있다.</p>



<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>
#include &lt;list>

using namespace std;

constexpr int INF = INT32_MAX / 2;

constexpr int MAX = 251;

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

list&lt;pair&lt;int, int>> myList;

int disArr[MAX][MAX];

// N : 도시의 수, M : 길의 수
int N, M, s, d, w, b, K, result;

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

	cin >> N >> M;

	// 최단 거리 배열 disArr 배열을 INF 초기화
	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {
			disArr[i][j] = INF;
		}
	}

	// 길의 정보를 입력
	for (int i = 0; i &lt; M; i++) {

		// 출발 s, 도착 d, b 양/단 방향
		cin >> s >> d >> b;

		if (b == 0) { // 단방향
			graph[s].push_back(make_pair(d, 0));
			disArr[d][s] = 1; // (disArr[i][k] + disArr[k][j] vs INF)
		}
		else { // 양방향
			graph[s].push_back(make_pair(d, 0));
			graph[d].push_back(make_pair(s, 0));
		}

	}

	// 질문을 입력 받는다.
	cin >> K;

	pair&lt;int, int> tempP;

	while (K--) {
		cin >> tempP.first >> tempP.second;
		myList.push_back(tempP);
	}

	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][v] > weight) disArr[i][v] = weight;
		}
	}

	// 무지성 플로이드
	for (int k = 1; k &lt;= N; k++) {
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 1; j &lt;= N; j++) {

				if (i == j) disArr[i][j] = 0;
				else disArr[i][j] = min(disArr[i][j], disArr[i][k] + disArr[k][j]);

			}
		}
	}

	for (auto it = myList.begin(); it != myList.end(); it++) {
		cout &lt;&lt; disArr[it->first][it->second] &lt;&lt; "\n";		
	}

	return 0;
}</pre>



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



<figure class="wp-block-image size-full is-resized"><img decoding="async" src="https://lycos7560.com/wp-content/uploads/2023/02/image-81.png" alt="" class="wp-image-33220" width="1192" height="166" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-81.png 917w, https://lycos7560.com/wp-content/uploads/2023/02/image-81-300x42.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-81-768x107.png 768w" sizes="(max-width: 1192px) 100vw, 1192px" /></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-11562%eb%b2%88-%eb%b0%b1%ec%96%91%eb%a1%9c-%eb%b8%8c%eb%a0%88%ec%9d%b4%ed%81%ac-c-floyd-warshall-baekjoon/33218/">백준 11562번 (백양로 브레이크, C++, Floyd-Warshall) [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-11562%eb%b2%88-%eb%b0%b1%ec%96%91%eb%a1%9c-%eb%b8%8c%eb%a0%88%ec%9d%b4%ed%81%ac-c-floyd-warshall-baekjoon/33218/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 11404번 (플로이드, C++, Floyd-Warshall) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11404%eb%b2%88-%ed%94%8c%eb%a1%9c%ec%9d%b4%eb%93%9c-c-floyd-warshall-baekjoon/33213/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11404%eb%b2%88-%ed%94%8c%eb%a1%9c%ec%9d%b4%eb%93%9c-c-floyd-warshall-baekjoon/33213/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 17 Feb 2023 02:12:37 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[11404]]></category>
		<category><![CDATA[11404번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Floyd-Warshall]]></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[백준 11404]]></category>
		<category><![CDATA[백준 11404번]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[플로이드]]></category>
		<category><![CDATA[플로이드 워셜]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=33213</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 11404번 '플로이드' 문제에 대한 글입니다. 'Floyd-Warshall' 알고리즘을 이용하여 해결하였습니다. (This is an article about the 'Floyd' problem in BAEKJOON 11404. Solved using the 'Floyd-Warshall' algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11404%eb%b2%88-%ed%94%8c%eb%a1%9c%ec%9d%b4%eb%93%9c-c-floyd-warshall-baekjoon/33213/">백준 11404번 (플로이드, C++, Floyd-Warshall) [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-9bb9666b      "
					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/11404" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/11404</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">50776</td><td class="has-text-align-left" data-align="left">21108</td><td class="has-text-align-left" data-align="left">14907</td><td class="has-text-align-left" data-align="left">41.664%</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(2 ≤ n ≤ 100)개의 도시가 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">그리고 한 도시에서 출발하여 다른 도시에 도착하는 m(1 ≤ m ≤ 100,000)개의 버스가 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">각 버스는 한 번 사용할 때 필요한 비용이 있다.</p>



<p class="has-medium-font-size wp-block-paragraph">모든 도시의 쌍 (A, B)에 대해서 도시 A에서 B로 가는데 필요한 비용의 최솟값을 구하는 프로그램을 작성하시오.</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+2줄까지 다음과 같은 버스의 정보가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">버스의 정보는 버스의 시작 도시 a, 도착 도시 b, 한 번 타는데 필요한 비용 c로 이루어져 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">시작 도시와 도착 도시가 같은 경우는 없다. </p>



<p class="has-medium-font-size wp-block-paragraph">비용은 100,000보다 작거나 같은 자연수이다.</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개의 줄을 출력해야 한다. </p>



<p class="has-medium-font-size wp-block-paragraph">i번째 줄에 출력하는 j번째 숫자는 도시 i에서 j로 가는데 필요한 최소 비용이다.</p>



<p class="has-medium-font-size wp-block-paragraph">만약, i에서 j로 갈 수 없는 경우에는 그 자리에 0을 출력한다.</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
14
1 2 2
1 3 3
1 4 1
1 5 10
2 4 2
3 4 1
3 5 1
4 5 3
3 5 10
3 1 8
1 4 2
5 1 7
3 4 2
5 2 4</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="">0 2 3 1 4
12 0 15 2 5
8 5 0 1 1
10 7 13 0 3
7 4 10 6 0</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>문제의 오타를 찾은 사람: <a href="https://www.acmicpc.net/user/algoshipda" target="_blank" rel="noreferrer noopener">algoshipda</a></li>



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



<li>빠진 조건을 찾은 사람: <a href="https://www.acmicpc.net/user/dbfldkfdbgml" target="_blank" rel="noreferrer noopener">dbfldkfdbgml</a>, <a href="https://www.acmicpc.net/user/koosaga" target="_blank" rel="noreferrer noopener">koosaga</a></li>



<li>데이터를 추가한 사람: <a href="https://www.acmicpc.net/user/dlwocks31" target="_blank" rel="noreferrer noopener">dlwocks31</a>, <a href="https://www.acmicpc.net/user/kyaryunha_cpp" target="_blank" rel="noreferrer noopener">kyaryunha_cpp</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/31" 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="1600" height="1456" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_110728324.jpg" alt="" class="wp-image-33216" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_110728324.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_110728324-300x273.jpg 300w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_110728324-768x699.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230217_110728324-1536x1398.jpg 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></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 int INF = INT32_MAX/2; // overflow 조

constexpr int MAX = 101;

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

int disArr[MAX][MAX];

// N : 도시의 수, M : 버스의 수
int N, M, s, d, w;

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

	cin >> N >> M;

	// 노선을 입력
	for (int i = 0; i &lt; M; i++) {

		// 단방향 교통수단 출발 s, 도착 d, 비용 w
		cin >> s >> d >> w;

		graph[s].push_back(make_pair(d, w));
	}

	// 최단 거리 배열 disArr 배열을 INF 초기화
	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {

			if (i == j) disArr[i][j] = 0;
			else disArr[i][j] = INF;

		}
	}

	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][v] > weight) 	disArr[i][v] = weight;

		}
	}
	
	// 무지성 플로이드
	for (int k = 1; k &lt;= N; k++) {
		for (int i = 1; i &lt;= N; i++) {
			for (int j = 1; j &lt;= N; j++) {

				if (i == j) disArr[i][j] = 0;
				else disArr[i][j] = min(disArr[i][j], disArr[i][k] + disArr[k][j]);

			}
		}
	}

	// 결과 출력
	for (int i = 1; i &lt;= N; i++) {
		for (int j = 1; j &lt;= N; j++) {

			if (disArr[i][j] == INF) cout &lt;&lt; 0 &lt;&lt; " ";
			else cout &lt;&lt; disArr[i][j] &lt;&lt; " ";

		}

		cout &lt;&lt; "\n";

	}

	return 0;
}</pre>



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



<figure class="wp-block-image size-full is-resized"><img decoding="async" src="https://lycos7560.com/wp-content/uploads/2023/02/image-80.png" alt="" class="wp-image-33214" width="982" height="89" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-80.png 912w, https://lycos7560.com/wp-content/uploads/2023/02/image-80-300x27.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-80-768x70.png 768w" sizes="(max-width: 982px) 100vw, 982px" /></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-11404%eb%b2%88-%ed%94%8c%eb%a1%9c%ec%9d%b4%eb%93%9c-c-floyd-warshall-baekjoon/33213/">백준 11404번 (플로이드, C++, Floyd-Warshall) [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-11404%eb%b2%88-%ed%94%8c%eb%a1%9c%ec%9d%b4%eb%93%9c-c-floyd-warshall-baekjoon/33213/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 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>백준 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>
		<item>
		<title>백준 5719번 (거의 최단 경로, C++, Dijkstra) / 추가 반례 [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-5719%eb%b2%88-%ea%b1%b0%ec%9d%98-%ec%b5%9c%eb%8b%a8-%ea%b2%bd%eb%a1%9c-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/6006/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-5719%eb%b2%88-%ea%b1%b0%ec%9d%98-%ec%b5%9c%eb%8b%a8-%ea%b2%bd%eb%a1%9c-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/6006/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sun, 05 Feb 2023 13:45:54 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[5719]]></category>
		<category><![CDATA[5719번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cin.tie(NULL)]]></category>
		<category><![CDATA[cout.tie(NULL)]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Dijkstra]]></category>
		<category><![CDATA[DP]]></category>
		<category><![CDATA[DynamicProgramming]]></category>
		<category><![CDATA[priority_queue]]></category>
		<category><![CDATA[PriorityQueue]]></category>
		<category><![CDATA[Queue]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[vector]]></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>
		<category><![CDATA[데이크스트라]]></category>
		<category><![CDATA[반례]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 5719]]></category>
		<category><![CDATA[백준 5719번]]></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=6006</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 5719번 "거의 최단 경로" 문제에 대한 글입니다. Dijkstra 알고리즘을 이용하여 해결하였습니다. (This article is about the "near shortest path" problem in BAEKJOON No. 5719. It was solved using Dijkstra algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-5719%eb%b2%88-%ea%b1%b0%ec%9d%98-%ec%b5%9c%eb%8b%a8-%ea%b2%bd%eb%a1%9c-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/6006/">백준 5719번 (거의 최단 경로, C++, Dijkstra) / 추가 반례 [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-539bed31      "
					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: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/problem/5719" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/5719</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">23040</td><td class="has-text-align-left" data-align="left">3945</td><td class="has-text-align-left" data-align="left">2400</td><td class="has-text-align-left" data-align="left">19.151%</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">요즘 많은 자동차에서는 GPS 네비게이션 장비가 설치되어 있다. </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">예를 들어, 도로 지도가 아래와 같을 때를 생각해보자. </p>



<p class="has-medium-font-size wp-block-paragraph">원은 장소를 의미하고, 선은 단방향 도로를 나타낸다. </p>



<p class="has-medium-font-size wp-block-paragraph">시작점은 S, 도착점은 D로 표시되어 있다. 굵은 선은 최단 경로를 나타낸다. (아래 그림에 최단 경로는 두 개가 있다)</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">예를 들어, 아래 그림의 길이가 3인 도로의 길이가 1이라면, 거의 최단 경로는 두 개가 된다. </p>



<p class="has-medium-font-size wp-block-paragraph">또, 거의 최단 경로가 없는 경우도 있다.</p>



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



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



<div style="height:20px" 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">각 테스트 케이스의 첫째 줄에는 장소의 수 N (2 ≤ N ≤ 500)과 도로의 수 M (1 ≤ M ≤ 10<sup>4</sup>)가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">장소는 0부터 N-1번까지 번호가 매겨져 있다. 둘째 줄에는 시작점 S와 도착점 D가 주어진다. (S ≠ D; 0 ≤ S, D &lt; N) </p>



<p class="has-medium-font-size wp-block-paragraph">다음 M개 줄에는 도로의 정보 U, V, P가 주어진다. (U ≠ V ; 0 ≤ U, V &lt; N; 1 ≤ P ≤ 10<sup>3</sup>) </p>



<p class="has-medium-font-size wp-block-paragraph">이 뜻은 U에서 V로 가는 도로의 길이가 P라는 뜻이다. </p>



<p class="has-medium-font-size wp-block-paragraph">U에서 V로 가는 도로는 최대 한 개이다. </p>



<p class="has-medium-font-size wp-block-paragraph">또, U에서 V로 가는 도로와 V에서 U로 가는 도로는 다른 도로이다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">입력의 마지막 줄에는 0이 두 개 주어진다.</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">만약, 거의 최단 경로가 없는 경우에는 -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="">7 9
0 6
0 1 1
0 2 1
0 3 2
0 4 3
1 5 2
2 6 4
3 6 2
4 6 4
5 6 1
4 6
0 2
0 1 1
1 2 1
1 3 1
3 2 1
2 0 3
3 0 2
6 8
0 1
0 1 1
0 2 2
0 3 3
2 5 3
3 4 2
4 1 1
5 1 1
3 0 1
0 0</pre>



<div style="height:20px" 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
-1
6</pre>



<div style="height:50px" 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/1" target="_blank" rel="noreferrer noopener">ICPC</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/7" target="_blank" rel="noreferrer noopener">Regionals</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/103" target="_blank" rel="noreferrer noopener">Latin America</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/568" target="_blank" rel="noreferrer noopener">South America Regional Contests 2008</a>&nbsp;A번</p>



<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/gkswjdzz" target="_blank" rel="noreferrer noopener">gkswjdzz</a>,&nbsp;<a href="https://www.acmicpc.net/user/sait2000" target="_blank" rel="noreferrer noopener">sait2000</a>,&nbsp;<a href="https://www.acmicpc.net/user/smsm8111" target="_blank" rel="noreferrer noopener">smsm8111</a></li>



<li>잘못된 데이터를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/tncks0121" target="_blank" rel="noreferrer noopener">tncks0121</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/22" 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>



<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="">100 765
44 52
0 11 939
0 18 635
0 26 757
0 39 558
0 41 669
0 43 855
0 45 951
0 46 755
0 51 785
0 52 218
0 78 557
0 94 918
0 96 300
1 19 752
1 22 157
1 31 797
1 37 871
1 78 834
2 0 275
2 30 73
2 64 32
2 67 552
2 78 7
2 81 883
2 96 315
2 99 865
3 11 299
3 13 196
3 37 247
3 45 523
3 47 745
3 54 474
3 60 63
3 94 244
3 97 699
3 99 855
4 10 516
4 17 506
4 24 985
4 28 598
4 35 598
4 39 744
4 44 749
4 46 8
4 77 363
4 78 618
4 92 988
4 97 591
5 0 918
5 9 8
5 14 405
5 23 448
5 84 354
6 0 404
6 10 209
6 20 352
6 57 651
6 71 490
6 77 934
6 94 188
6 96 638
6 99 138
7 25 815
7 27 55
7 42 606
7 56 643
7 65 966
7 81 755
8 0 684
8 5 959
8 13 998
8 19 757
8 22 172
8 33 638
8 38 777
8 51 185
8 59 321
8 67 403
8 69 475
8 71 204
8 74 567
8 97 138
9 15 965
9 17 611
9 64 712
9 66 743
9 84 971
10 5 486
11 3 678
11 54 838
11 86 226
11 95 623
12 5 427
12 28 19
12 33 879
12 35 876
12 37 907
12 50 437
12 51 853
12 52 407
12 58 756
12 68 480
12 75 867
12 85 833
13 6 356
13 37 954
13 53 479
13 68 448
13 74 707
13 79 369
13 80 735
13 84 17
13 96 355
14 6 185
14 12 121
14 17 925
14 32 276
14 36 559
14 39 343
14 44 90
14 86 513
14 87 952
14 96 912
15 13 296
15 20 726
15 36 835
15 41 458
15 49 17
15 57 47
15 61 583
15 65 25
15 82 703
16 9 289
16 19 289
16 26 935
16 46 122
16 58 611
16 59 625
16 60 89
16 75 674
16 81 147
16 85 806
16 86 89
17 7 848
17 39 490
17 53 980
17 58 372
17 62 357
17 78 885
17 83 406
17 87 873
17 95 32
18 41 232
18 43 394
18 47 35
18 50 697
18 83 464
18 87 281
19 1 857
19 12 589
19 14 819
19 37 470
19 40 520
19 42 276
19 43 27
19 66 706
19 71 426
19 83 858
19 94 353
20 13 523
20 17 128
20 51 90
20 53 411
20 84 903
20 91 747
20 96 503
21 23 721
21 27 724
21 28 34
21 30 396
21 34 86
21 37 371
21 53 371
21 54 672
22 4 325
22 11 407
22 44 631
22 55 480
22 68 861
22 90 338
23 1 109
23 15 850
23 34 645
23 48 582
23 52 264
23 58 330
23 64 796
23 65 118
23 69 133
23 89 389
24 11 220
24 26 5
24 38 951
24 44 990
24 45 123
24 49 216
24 51 505
24 90 388
24 93 475
25 24 633
25 41 489
25 83 434
26 4 577
26 17 977
26 19 558
26 31 863
26 33 284
26 43 751
26 46 576
26 48 224
26 79 497
27 14 26
27 18 949
27 21 102
27 38 357
27 45 528
27 75 614
27 76 289
27 80 803
27 81 343
28 3 458
28 15 893
28 24 579
28 44 649
28 62 934
28 65 964
28 67 177
28 87 678
29 0 191
29 39 112
29 45 184
29 61 778
29 87 810
30 4 335
30 11 829
30 50 996
30 54 470
30 60 972
30 63 147
30 98 559
30 99 24
31 15 30
31 29 250
31 46 53
31 63 488
31 71 561
32 35 812
32 50 781
32 67 540
33 34 611
33 56 12
33 61 631
33 64 842
33 89 697
34 4 208
34 19 621
34 23 343
34 35 129
34 40 489
34 42 323
34 56 762
34 64 522
34 79 412
35 1 64
35 3 799
35 5 360
35 6 488
35 11 879
35 27 403
35 28 320
35 43 802
35 71 639
35 75 147
35 94 310
36 3 471
36 18 920
36 37 260
36 51 987
36 68 888
36 77 573
37 5 79
37 24 306
37 51 731
37 54 451
38 34 359
38 35 854
38 48 903
38 71 322
38 99 262
39 5 40
39 6 830
39 8 58
39 22 757
39 23 539
39 36 984
39 58 75
39 60 780
39 63 223
39 65 365
39 66 86
39 67 953
39 78 705
39 79 505
39 87 29
39 94 31
39 97 865
40 11 60
40 49 145
40 57 211
40 60 371
40 81 144
40 82 874
40 97 994
41 37 142
41 99 976
42 4 376
42 8 56
42 12 372
42 28 634
42 30 71
42 35 766
42 43 653
42 45 283
42 47 674
42 52 807
42 57 189
42 84 279
42 86 366
42 91 728
42 93 702
43 6 149
43 14 39
43 40 796
43 87 35
43 89 946
43 94 259
43 95 375
44 8 35
44 21 605
44 25 809
44 73 418
44 85 914
44 93 368
45 34 90
45 41 172
45 48 253
45 53 829
45 65 31
45 86 994
45 92 826
46 18 346
46 37 161
46 44 505
46 76 992
46 80 576
46 94 984
47 8 295
47 35 330
47 56 954
47 76 158
47 77 39
47 80 313
47 82 217
47 87 688
48 17 214
48 31 760
48 36 989
48 37 922
48 84 886
49 12 757
49 14 724
49 16 948
49 34 854
49 38 552
49 40 361
49 50 990
49 53 148
49 74 959
49 82 226
49 84 153
49 87 134
50 14 838
50 33 260
50 37 624
50 44 381
50 47 868
50 55 616
50 90 135
50 92 148
50 97 510
51 56 459
51 84 726
51 91 543
51 99 855
52 2 872
52 23 771
52 35 380
52 76 773
52 81 769
53 10 314
53 48 745
53 49 567
53 50 99
53 58 180
53 67 297
53 80 107
54 17 458
54 21 310
54 44 68
54 70 896
54 83 986
54 87 605
54 90 422
55 0 101
55 7 868
55 31 316
55 36 208
55 46 151
55 87 612
56 0 40
56 16 247
56 35 492
56 59 609
56 73 796
56 78 225
57 2 419
57 17 785
57 23 523
57 37 730
57 42 290
57 47 503
57 59 909
57 81 319
57 84 782
57 95 250
58 2 842
58 26 886
58 52 168
58 56 386
58 59 253
58 70 174
58 79 608
58 81 764
58 89 215
59 8 105
59 9 876
59 18 305
59 20 397
59 31 278
59 35 379
59 57 702
60 18 785
60 59 603
60 62 224
60 63 300
60 69 111
60 70 437
60 86 129
60 88 862
60 90 603
61 13 185
61 14 521
61 26 23
61 33 645
61 45 907
61 67 269
61 75 717
61 82 919
61 90 554
61 91 865
61 98 182
62 13 135
62 24 96
62 39 625
62 63 901
62 81 816
62 97 592
63 7 518
63 8 46
63 16 724
63 52 912
63 97 725
64 15 554
64 29 395
64 35 177
64 38 340
64 58 100
64 66 570
64 76 754
65 24 370
65 29 726
65 33 348
65 41 388
65 44 931
65 59 293
65 92 255
65 95 937
66 7 435
66 17 260
66 19 510
66 23 571
66 25 875
66 39 671
66 77 97
66 80 52
66 82 939
67 2 110
67 40 346
67 41 641
67 46 881
67 52 703
67 58 770
67 62 974
67 81 199
67 90 396
67 95 558
67 96 375
67 99 597
68 2 395
68 17 863
68 20 8
68 22 682
68 43 444
68 74 870
68 79 739
68 98 158
69 10 763
69 13 933
69 25 738
69 28 755
69 33 745
69 53 998
69 58 961
69 78 410
69 89 621
69 90 271
69 91 362
69 98 574
70 17 788
70 38 695
70 44 383
70 55 843
70 60 373
70 61 529
71 7 932
71 9 184
71 25 341
71 27 360
71 53 832
71 60 135
71 64 245
71 69 980
71 72 238
71 74 210
72 14 63
72 42 346
72 60 204
72 71 324
72 73 970
72 88 547
72 90 618
73 9 20
73 17 980
73 18 845
73 27 728
73 37 577
73 46 472
73 56 825
73 58 111
73 61 962
73 75 69
73 86 389
74 10 720
74 17 31
74 67 163
74 69 621
74 79 831
74 84 479
74 88 579
74 91 43
75 18 763
75 24 669
75 33 618
75 61 689
75 78 430
75 83 422
76 1 768
76 31 972
76 69 445
76 73 111
76 75 841
76 78 529
76 86 614
76 91 841
77 5 158
77 14 396
77 20 358
77 37 436
77 51 954
77 52 316
77 55 782
77 88 65
77 99 451
78 9 753
78 38 838
78 91 373
79 23 788
79 30 901
79 48 428
79 84 193
79 85 396
79 88 456
80 6 442
80 10 869
80 29 590
80 32 894
80 45 429
80 67 2
80 74 800
80 90 257
81 12 6
81 27 306
81 35 908
81 68 610
81 69 629
81 78 320
81 88 385
81 90 337
81 96 483
82 30 690
82 53 871
82 61 713
82 97 228
82 99 199
83 34 654
83 39 786
83 46 529
83 53 429
83 76 995
83 82 802
83 84 571
84 0 362
84 6 696
84 19 298
84 30 741
84 34 286
84 54 31
84 58 194
84 61 383
84 81 487
84 88 656
84 95 750
84 98 916
84 99 819
85 6 716
85 38 723
85 43 889
85 44 775
85 57 115
85 68 548
85 77 480
86 23 988
86 41 963
86 49 512
86 62 210
86 89 363
86 92 738
86 96 942
87 7 666
87 22 689
87 26 53
87 50 675
87 54 297
87 82 997
87 83 883
88 23 942
88 43 622
88 52 24
88 61 777
88 63 58
88 79 708
88 92 637
89 19 853
89 29 912
89 42 95
90 16 517
90 18 18
90 19 115
90 40 979
90 56 780
90 84 13
90 86 926
91 15 816
91 17 998
91 32 554
91 39 131
91 44 928
91 59 707
91 70 288
91 75 906
92 16 936
92 35 45
92 46 541
92 51 871
92 55 982
92 63 362
92 70 453
92 72 376
92 75 370
92 79 973
92 96 986
93 3 705
93 15 801
93 23 894
93 49 26
93 50 974
93 56 925
93 94 558
94 0 893
94 33 130
94 34 520
94 35 382
94 47 352
94 50 1
94 56 922
94 57 844
94 62 854
94 79 87
95 33 836
95 36 728
95 46 558
95 57 134
95 73 232
95 75 191
96 17 846
96 72 506
97 11 623
97 46 668
97 60 739
97 63 937
97 86 2
97 95 87
98 22 60
98 25 409
98 53 509
98 61 96
98 83 660
98 86 889
99 45 624
99 47 589
99 51 300
99 58 248
99 77 867
99 78 769
99 80 566
0 0</pre>



<div style="height:20px" 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="">726</pre>



<div style="height:50px" 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="">4 5
0 2
0 1 1
0 3 5
1 2 1
1 3 1
3 2 1
4 5
0 2
0 1 1
0 3 5
1 2 2
1 3 1
3 2 1
4 5
0 2
0 1 5
0 3 1
1 2 1
3 1 1
3 2 2
5 6
0 1
0 1 1
0 2 1
0 4 1
2 3 1
3 1 1
4 1 2
0 0</pre>



<div style="height:20px" 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="">6
-1
-1
3</pre>



<div style="height:50px" 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 6
0 1
0 1 1
0 2 1
0 4 1
2 3 1
3 1 1
4 1 1
5 6
0 1
0 1 3
0 2 1
0 4 1
2 3 1
3 1 1
4 1 2
4 6
0 3
0 1 1
0 2 1
1 0 1
1 2 1
2 0 1
2 1 1
3 6
0 2
0 1 1
0 2 1
1 0 1
1 2 1
2 0 1
2 1 1
0 0</pre>



<div style="height:20px" 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="">2
-1
-1
2</pre>



<div style="height:50px" 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="">3 2
0 2
0 1 1
1 2 1
5 6
0 1
0 1 1
0 2 1
2 3 1
2 4 1
3 1 1
4 1 1
4 6
0 3
0 1 1
0 2 1
0 3 1
1 2 1
1 3 1
2 3 1
4 6
0 3
0 1 1
0 2 2
0 3 3
1 2 1
1 3 2
2 3 1
0 0</pre>



<div style="height:20px" 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
3
2
-1</pre>



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



<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>



<p class="has-medium-font-size wp-block-paragraph">다익스트라의 경로를 저장하기 위하여 우선 순위 큐에 지나온 정점들을  list&lt;pair&lt;int, int&gt;&gt;에 담아 보았다. </p>



<p class="has-medium-font-size wp-block-paragraph">당연하게 메모리 초과 (정답은 잘나온다&#8230; ㅜㅜ)</p>



<p class="has-medium-font-size wp-block-paragraph">원리는 list에 있는 정점들을 방문처리하여 다음 다익스트라를 사용할 때 넘기는 방법을 사용했다.</p>



<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;queue>
#include &lt;vector>
#include &lt;list>
#include &lt;tuple>
#include &lt;map>

using namespace std;

constexpr int INF = INT32_MAX;

int disArr[501];

bool check[501][501];

int N, M, S, D, U, V, P;

int Dijstra()
{
    int result = INF;

    for (int i = 0; i &lt;= N; i++) {
        for (int j = 0; j &lt;= N; j++) {
            check[i][j] = false;
        }
    }

    // 임시배열 초기화
    for (int i = 0; i &lt;= N; i++) disArr[i] = INF;

    priority_queue&lt;tuple&lt;int, int, list&lt;pair&lt;int, int>>>> firstPQ;

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

    list&lt;pair&lt;int, int>> myList;

    multimap&lt;int, list&lt;pair&lt;int, int>>> myMap;

    for (int i = 0; i &lt; M; i++) {
        cin >> U >> V >> P;
        graph[U].push_back(make_pair(V, P));
    }

    // 우선순위 큐에 삽입.
    firstPQ.push({ 0, S, myList }); // &lt; first : 거리 , second : 노드 인덱스 >
    disArr[S] = 0;
    while (!firstPQ.empty()) {
        // -를 붙이는 이유는 우선순위 큐를 이용하여 정렬하기 위함이다.
        // (최소힙으로 구현)
        int nCost = -get&lt;0>(firstPQ.top());
        int now = get&lt;1>(firstPQ.top());
        myList = get&lt;2>(firstPQ.top());
        firstPQ.pop();

        // 이미 담겨 있는 것보다 거리가 크면 넘어간다.
        if (disArr[now] &lt; nCost) continue;

        // 해당 노드에서 연결된 모든 경로를 확인
        for (int i = 0; i &lt; graph[now].size(); i++) {
            list&lt;pair&lt;int, int>> tempList = myList;
            // disSum = 임시 노드 + 현재 노드에서 i로가는 비용
            int disSum = nCost + graph[now][i].second;

            // 비용이 더 작다면 최단경로 테이블 값을 갱신.
            if (disSum &lt;= disArr[graph[now][i].first]) {
                tempList.push_back(make_pair(now, graph[now][i].first));

                if (graph[now][i].first == D &amp;&amp; result >= disSum) {
                    result = disSum;
                    myMap.insert(make_pair(disSum, tempList));
                }

                // 임시 노드 업데이트
                disArr[graph[now][i].first] = disSum;
                // 우선순위 큐에 (거리, 노드 인덱스) 푸시
                firstPQ.push(make_tuple(-disSum, graph[now][i].first, tempList));
            }
        }
    }

    result = disArr[D];

    for (auto mit = myMap.begin(); mit != myMap.end(); mit++) {
        if (result == mit->first) {
            for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
                check[it->first][it->second] = true;
            }
        }

        else break;
    }

    priority_queue&lt;pair&lt;int, int>> myPQ;

    // 임시배열 초기화
    for (int i = 0; i &lt;= N; i++) disArr[i] = INF;

    // 우선순위 큐에 삽입.
    myPQ.push({ 0, S }); // &lt; first : 거리 , second : 노드 인덱스 >
    disArr[S] = 0;

    while (!myPQ.empty()) {
        // -를 붙이는 이유는 우선순위 큐를 이용하여 정렬하기 위함이다.
        // (최소힙으로 구현)
        int nCost = -myPQ.top().first;
        int now = myPQ.top().second;
        myPQ.pop();

        // 이미 담겨 있는 것보다 거리가 크면 넘어간다.
        if (disArr[now] &lt; nCost) continue;
        // 해당 노드에서 연결된 모든 경로를 확인
        for (int i = 0; i &lt; graph[now].size(); i++) {
            if (check[now][graph[now][i].first] == true) continue;
            // disSum = 임시 노드 + 현재 노드에서 i로가는 비용
            int disSum = nCost + graph[now][i].second;
            // 비용이 더 작다면 최단경로 테이블 값을 갱신.
            if (disSum &lt;= disArr[graph[now][i].first]) {
                // 임시 노드 업데이트
                disArr[graph[now][i].first] = disSum;
                // 우선순위 큐에 (거리, 노드 인덱스) 푸시
                myPQ.push(make_pair(-disSum, graph[now][i].first));
            }
        }
    }

    return disArr[D];
}


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

    while (true) {

        cin >> N >> M;

        if (N == 0 &amp;&amp; M == 0) break;

        cin >> S >> D;

        int result = Dijstra();

        if (result == INF) cout &lt;&lt; -1 &lt;&lt; "\n";
        else cout &lt;&lt; result &lt;&lt; "\n";
    }



    return 0;
}</pre>



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



<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>



<p class="has-medium-font-size wp-block-paragraph">vector&lt;int&gt; trace[501]; 를 이용하여 시작과 끝의 정점들을 넣어준다.</p>



<p class="has-medium-font-size wp-block-paragraph">주의할 점은 도착지에서 출발지 방향으로 탐색을 하기 위해서 반대로 넣어주어야 한다.</p>



<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;queue>
#include &lt;vector>

using namespace std;

constexpr int INF = INT32_MAX;

int disArr[501];

priority_queue&lt;pair&lt;int, int>> mypq;

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

vector&lt;int> trace[501];

int N, M, S, D, U, V, P;

void MyDijstra()
{  
    for (int i = 0; i &lt;= N; i++) disArr[i] = INF;

    for (int i = 0; i &lt; M; i++) {
        cin >> U >> V >> P;
        graph[U].push_back(make_pair(V, P));
    }

    // 우선순위 큐에 삽입.
    mypq.push({ 0, S }); // &lt; first : 거리 , second : 노드 인덱스 >

    disArr[S] = 0;

    while (!mypq.empty()) {
        // -를 붙이는 이유는 우선순위 큐를 이용하여 정렬하기 위함이다.
        // (최소힙으로 구현)
        int ncost = -mypq.top().first;
        int now = mypq.top().second;

        mypq.pop();

        // 이미 담겨 있는 것보다 거리가 크면 넘어간다.
        if (disArr[now] &lt; ncost) continue;

        // 해당 노드에서 연결된 모든 경로를 확인
        for (int i = 0; i &lt; graph[now].size(); i++) {
            // dissum = 임시 노드 + 현재 노드에서 i로가는 비용
            int dissum = ncost + graph[now][i].second;
            // 비용이 더 작다면 최단경로 테이블 값을 갱신.
            // 같아도 확인이 필요하다.
            // 최소 거리가 여러개 있을 수 있기 떄문
            if (dissum &lt;= disArr[graph[now][i].first]) {

                if (dissum &lt; disArr[graph[now][i].first]) {
                
                    // 임시 노드 업데이트
                    disArr[graph[now][i].first] = dissum;

                    trace[graph[now][i].first].clear(); // 새로 갱신한다면 전에 있던 것이 필요가 없다.
                    trace[graph[now][i].first].push_back(now); // 경로를 저장

                    // 우선순위 큐에 (거리, 노드 인덱스) 푸시
                    mypq.push(make_pair(-dissum, graph[now][i].first));
                }
                else trace[graph[now][i].first].push_back(now); // 경로를 저장 역방향으로 넣어준다.
            }
        }
    }

    // 최단 거리의 경로를 삭제해 줍니다.
    queue&lt;int> delQ;
    delQ.push(D);
    while (!delQ.empty()) {
        int nowDel = delQ.front();
        delQ.pop();
        for (int i = 0; i &lt; trace[nowDel].size(); i++) {
            for (auto it = graph[trace[nowDel][i]].begin(); it != graph[trace[nowDel][i]].end(); it++) {
                if ((*it).first == nowDel) {
                    delQ.push(trace[nowDel][i]);
                    graph[trace[nowDel][i]].erase(it);
                    break;
                }
            }
        }
    }


    // 새로운 데이크스트라를 진행하여 거의 최단 경로를 찾는다.
    for (int i = 0; i &lt;= N; i++) disArr[i] = INF;
    // 우선순위 큐에 삽입.
    mypq.push({ 0, S }); // first : 거리 , second : 노드 인덱스
    disArr[S] = 0;
    while (!mypq.empty()) {
        // -를 붙이는 이유는 우선순위 큐를 이용하여 정렬하기 위함이다.
        // (최소힙으로 구현)
        int ncost = -mypq.top().first;
        int now = mypq.top().second;

        mypq.pop();

        // 이미 담겨 있는 것보다 거리가 크면 넘어간다.
        if (disArr[now] &lt; ncost) continue;

        // 해당 노드에서 연결된 모든 경로를 확인
        for (int i = 0; i &lt; graph[now].size(); i++) {
            // dissum = 임시 노드 + 현재 노드에서 i로가는 비용
            int dissum = ncost + graph[now][i].second;
            // 비용이 더 작다면 최단경로 테이블 값을 갱신.
            if (dissum &lt; disArr[graph[now][i].first]) {

                disArr[graph[now][i].first] = dissum;
                // 우선순위 큐에 (거리, 노드 인덱스) 푸시
                mypq.push(make_pair(-dissum, graph[now][i].first));
            }
        }
    }

    for (int i = 0; i &lt;= N; i++) trace[i].clear();
    for (int i = 0; i &lt;= M; i++) graph[i].clear();
}


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

    while (true) {

        cin >> N >> M;

        if (N == 0 &amp;&amp; M == 0) break;

        cin >> S >> D;

        MyDijstra();

        if (disArr[D] == INF) cout &lt;&lt; -1 &lt;&lt; "\n";
        else cout &lt;&lt; disArr[D] &lt;&lt; "\n";
    }

    return 0;
}</pre>



<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="1026" height="758" src="https://lycos7560.com/wp-content/uploads/2023/02/image-35.png" alt="" class="wp-image-6012" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-35.png 1026w, https://lycos7560.com/wp-content/uploads/2023/02/image-35-300x222.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-35-768x567.png 768w" sizes="(max-width: 1026px) 100vw, 1026px" /></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>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-5719%eb%b2%88-%ea%b1%b0%ec%9d%98-%ec%b5%9c%eb%8b%a8-%ea%b2%bd%eb%a1%9c-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/6006/">백준 5719번 (거의 최단 경로, C++, Dijkstra) / 추가 반례 [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-5719%eb%b2%88-%ea%b1%b0%ec%9d%98-%ec%b5%9c%eb%8b%a8-%ea%b2%bd%eb%a1%9c-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/6006/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 10217번 (KCM Travel, C++, Dijkstra) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-10217%eb%b2%88-kcm-travel-c-dijkstra-baekjoon/5982/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-10217%eb%b2%88-kcm-travel-c-dijkstra-baekjoon/5982/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 03 Feb 2023 05:07:07 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[10217]]></category>
		<category><![CDATA[10217번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cin.tie(NULL)]]></category>
		<category><![CDATA[cout.tie(NULL)]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Dijkstra]]></category>
		<category><![CDATA[DP]]></category>
		<category><![CDATA[DynamicProgramming]]></category>
		<category><![CDATA[KCM Travel]]></category>
		<category><![CDATA[priority_queue]]></category>
		<category><![CDATA[PriorityQueue]]></category>
		<category><![CDATA[Queue]]></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>
		<category><![CDATA[데이크스트라]]></category>
		<category><![CDATA[도로포장]]></category>
		<category><![CDATA[반례]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 10217]]></category>
		<category><![CDATA[백준 10217번]]></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=5982</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 10217번 'KCM Travel' 문제에 대한 글입니다. Dijkstra 알고리즘을 이용하여 해결하였습니다. (This is an article about the 'KCM Travel' problem in BAEKJOON 10217. It was solved using Dijkstra algorithm.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-10217%eb%b2%88-kcm-travel-c-dijkstra-baekjoon/5982/">백준 10217번 (KCM Travel, C++, Dijkstra) [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-0e7c2a87      "
					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="#kcm-travel" class="uagb-toc-link__trigger">KCM Travel</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><li 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="#예제-출력-1" class="uagb-toc-link__trigger">예제 출력 1</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><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><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#재채점-이후" class="uagb-toc-link__trigger">재채점 이후</a></ul></ol>					</div>
									</div>
				</div>
			


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



<h1 class="wp-block-heading">KCM Travel</h1>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/10217" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/10217</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">10 초</td><td class="has-text-align-left" data-align="left">256 MB</td><td class="has-text-align-left" data-align="left">21759</td><td class="has-text-align-left" data-align="left">4834</td><td class="has-text-align-left" data-align="left">2300</td><td class="has-text-align-left" data-align="left">17.114%</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">각고의 노력 끝에 찬민이는 2014 Google Code Jam World Finals에 진출하게 되었다.&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">초대장 내용에 의하면 구글은 찬민에게 최대 M원까지의 비용만을 여행비로써 부담해주겠다고 한다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">인천에서 LA행 직항 한 번 끊어주는게 그렇게 힘드냐고 따지고도 싶었지만, </p>



<p class="has-medium-font-size wp-block-paragraph">다가올 결승 대회를 생각하면 대회 외적인 곳에 마음을 쓰고 싶지 않은 것 또한 사실이었다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">그래서 찬민은 인천에서 LA까지 M원 이하로 사용하면서 도착할 수 있는 가장 빠른 길을 차선책으로 택하기로 하였다.</p>



<p class="has-medium-font-size wp-block-paragraph">각 공항들간 티켓가격과 이동시간이 주어질 때, </p>



<p class="has-medium-font-size wp-block-paragraph">찬민이 인천에서 LA로 갈 수 있는 가장 빠른 길을 찾아 찬민의 대회 참가를 도와주자.</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">입력 파일의 첫 번째 줄에 테스트 케이스의 수를 의미하는 자연수 T가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">그 다음에는 T개의 테스트 케이스가 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">각 테스트 케이스의 첫 줄에는 공항의 수 N (2 ≤ N ≤ 100), 총 지원비용 M (0 ≤ M ≤ 10,000), </p>



<p class="has-medium-font-size wp-block-paragraph">티켓정보의 수 K (0 ≤ K ≤ 10,000)가 공백으로 구분되어 주어진다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">이어서&nbsp;K개의 줄에 걸쳐 각 티켓의 출발공항 u, 도착공항 v (1 ≤ u, v ≤ N, u&nbsp;≠ v), 비용 c&nbsp;(1 ≤ c ≤ M, 정수), </p>



<p class="has-medium-font-size wp-block-paragraph">그리고 소요시간 d (1 ≤ d ≤ 1,000) 가 공백으로&nbsp;구분되어 주어진다.&nbsp;</p>



<p class="has-medium-font-size wp-block-paragraph">인천은 언제나 1번 도시이고, LA는 언제나 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">각 테스트 케이스당 한 줄에 찬민이 LA에 도착하는 데 걸리는&nbsp;가장 짧은 소요시간을 출력한다.</p>



<p class="has-medium-font-size wp-block-paragraph">만약, LA에 도착할 수 없는 경우 &#8220;Poor KCM&#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="">2
3 100 3
1 2 1 1
2 3 1 1
1 3 3 30
4 10 4
1 2 5 3
2 3 5 4
3 4 1 5
1 3 10 6</pre>



<div style="height:20px" 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
Poor KCM</pre>



<div style="height:50px" 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/45" target="_blank" rel="noreferrer noopener">Contest</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/215" target="_blank" rel="noreferrer noopener">Coder&#8217;s High</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/1280">Coder</a><a href="https://www.acmicpc.net/category/detail/1280" target="_blank" rel="noreferrer noopener">&#8216;</a><a href="https://www.acmicpc.net/category/detail/1280">s High 2014</a>&nbsp;D번</p>



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



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



<li>문제를 만든 사람:&nbsp;<a href="https://www.acmicpc.net/user/tae" target="_blank" rel="noreferrer noopener">tae</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/25" target="_blank" rel="noreferrer noopener">다이나믹 프로그래밍</a></li>



<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/22" 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)"/>



<h2 class="wp-block-heading">해결 방법</h2>



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



<figure class="wp-block-embed is-type-wp-embed"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="XUKUyEZE81"><a href="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1162%eb%b2%88-%eb%8f%84%eb%a1%9c%ed%8f%ac%ec%9e%a5-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/5955/">백준 1162번 (도로포장, C++, Dijkstra) / 추가 반례 [BAEKJOON]</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;백준 1162번 (도로포장, C++, Dijkstra) / 추가 반례 [BAEKJOON]&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1162%eb%b2%88-%eb%8f%84%eb%a1%9c%ed%8f%ac%ec%9e%a5-c-dijkstra-%ec%b6%94%ea%b0%80-%eb%b0%98%eb%a1%80-baekjoon/5955/embed/#?secret=O9IYrbEt7s#?secret=XUKUyEZE81" data-secret="XUKUyEZE81" 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>



<p class="has-medium-font-size wp-block-paragraph">1162번 도로포장 문제와 유사한 방법으로 해결하였다.</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="1600" height="1606" src="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1.jpg" alt="" class="wp-image-5995" srcset="https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1.jpg 1600w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1-300x300.jpg 300w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1-150x150.jpg 150w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1-768x771.jpg 768w, https://lycos7560.com/wp-content/uploads/2023/02/KakaoTalk_20230203_135946996-1-1530x1536.jpg 1530w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



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



<h2 class="wp-block-heading"><s>통과된 코드 </s>(재채점 이후 시간초과)</h2>



<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>
#include &lt;queue>
#include &lt;tuple>

using namespace std;

priority_queue&lt;tuple&lt;long long int, int, int>> myPQ;

long long int disArr[101][10001];

constexpr long long int INF = INT64_MAX;

int T, N, M, K, U, V, C, D, cnt;

long long int Dijstra()
{
    cin >> N >> M >> K;

    // 다익스트라 배열 초기화
    for (int i = 0; i &lt;= N; i++)
        for (int j = 0; j &lt;= M; j++)
            disArr[i][j] = INF;

    vector&lt;tuple&lt;int, int, int>> graph[10000];

    for (int i = 0; i &lt; K; i++) {
        cin >> U >> V >> C >> D;
        graph[U].push_back(make_tuple(V, C, D));
    }

    // 우선순위 큐에 삽입.
    myPQ.push({ 0, 1, 0 }); // &lt;거리 , 노드 인덱스 , 비용>

    disArr[1][0] = 0;

    while (!myPQ.empty()) {
        // -를 붙이는 이유는 우선순위 큐를 이용하여 정렬하기 위함이다.
        // (최소힙으로 구현)
        long long int nCost = -get&lt;0>(myPQ.top()); // 현재 최단 거리

        int now = get&lt;1>(myPQ.top()); // 현재 노드

        int money = get&lt;2>(myPQ.top()); // 비용 

        myPQ.pop();
        // 이미 담겨 있는 것보다 거리가 크면 넘어간다.
        if (disArr[now][money] &lt; nCost) continue;
        // 해당 노드에서 연결된 모든 경로를 확인
        for (int i = 0; i &lt; graph[now].size(); i++) {

            // 비용의 범위가 초과된다면 continue
            if (money + get&lt;1>(graph[now][i]) > M) continue;

            // disSum = 임시 노드 + 현재 노드에서 i로가는 비용
            long long int disSum = nCost + get&lt;2>(graph[now][i]);

            // 비용이 작다면 최단경로 테이블 값을 갱신.
            if (disSum &lt; disArr[get&lt;0>(graph[now][i])][money + get&lt;1>(graph[now][i])]) {
                // 임시 노드 업데이트
                disArr[get&lt;0>(graph[now][i])][money + get&lt;1>(graph[now][i])] = disSum;
                // 우선순위 큐에 (거리, 노드 인덱스, 비용) 푸시
                myPQ.push({ -disSum, get&lt;0>(graph[now][i]), money + get&lt;1>(graph[now][i]) });

            }
        }
    }

    long long int result = INF;

    for (int i = 0; i &lt;= M; i++) {
       result = min(disArr[N][i], result);
    }

    return result;
}


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

    cin >> T;

    while (T-- > 0) {
        long long int result = Dijstra();
        if (result == INF) cout &lt;&lt; "Poor KCM\n";
        else cout &lt;&lt; result &lt;&lt; "\n";
    }

    return 0;
}

</pre>



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



<figure class="wp-block-image size-full is-resized"><img decoding="async" width="1024" height="46" src="https://lycos7560.com/wp-content/uploads/2023/02/image-33.png" alt="" class="wp-image-5984" style="width:1134px;height:51px" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-33.png 1024w, https://lycos7560.com/wp-content/uploads/2023/02/image-33-300x13.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-33-768x35.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



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



<h2 class="wp-block-heading">재채점 이후 </h2>



<p class="wp-block-paragraph">deque을 이용하여 해결</p>



<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>
#include &lt;deque>
#include &lt;cstring>
#define INF 987654321

using namespace std;

struct Info {
    int node;  // 도착 공항
    int cost;  // 티켓 비용
    int time;  // 소요 시간
};

int n, m, k;
vector&lt;vector&lt;Info>> edges;
int dp[101][10001];  // dp[i][j]: i번 공항에 j 비용으로 도착했을 때 최소 소요 시간

void solve() {
    // 공항의 연결 정보 및 dp 배열 초기화
    edges.clear();
    edges.resize(n + 1);

    for (int i = 0; i &lt;= n; i++) {
        for (int j = 0; j &lt;= m; j++) {
            dp[i][j] = INF;
        }
    }

    // 티켓 정보 입력
    for (int i = 0; i &lt; k; i++) {
        int u, v, c, d;
        cin >> u >> v >> c >> d;
        edges[u].push_back({ v, c, d });
    }

    // deque를 사용한 BFS 기반 탐색 (비용과 시간을 함께 고려)
    deque&lt;pair&lt;int, pair&lt;int, int>>> dq;  // {소요 시간, {공항, 비용}}
    dq.push_back({ 0, {1, 0} });  // 시작점: 1번 공항, 비용 0, 소요 시간 0
    dp[1][0] = 0;  // 1번 공항, 비용 0에서 시작

    while (!dq.empty()) {
        int time = dq.front().first;
        int here = dq.front().second.first;
        int cost = dq.front().second.second;
        dq.pop_front();

        // 이미 더 빠른 경로가 있는 경우 스킵
        if (dp[here][cost] &lt; time) continue;

        // 현재 공항에서 갈 수 있는 다음 공항 탐색
        for (auto&amp; next_info : edges[here]) {
            int next = next_info.node;
            int next_time = time + next_info.time;
            int next_cost = cost + next_info.cost;

            // 비용이 초과하면 무시
            if (next_cost > m) continue;

            // 다음 공항에 대한 비용-시간 정보가 더 최적이면 갱신
            if (next_time &lt; dp[next][next_cost]) {
                dp[next][next_cost] = next_time;
                // deque에 삽입할 때, 비용이 더 낮은 경로를 우선으로 처리
                if (!dq.empty() &amp;&amp; dq.front().first > next_time) {
                    dq.push_front({ next_time, {next, next_cost} });
                }
                else {
                    dq.push_back({ next_time, {next, next_cost} });
                }
            }
        }
    }

    int answer = INF;

    // 목적지 공항 n에 비용 m 이하로 도착하는 최소 소요 시간 탐색
    for (int i = 0; i &lt;= m; i++) {
        answer = min(answer, dp[n][i]);
    }

    // 결과 출력: 도착할 수 없으면 "Poor KCM", 그렇지 않으면 최소 소요 시간 출력
    if (answer == INF) cout &lt;&lt; "Poor KCM" &lt;&lt; endl;
    else cout &lt;&lt; answer &lt;&lt; endl;
}

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

    int t;
    cin >> t;  // 테스트 케이스 입력
    while (t--) {
        cin >> n >> m >> k;  // 공항 수, 최대 지원 비용, 티켓 정보 수 입력
        solve();
    }

    return 0;
}
</pre>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-full"><img decoding="async" width="1155" height="762" src="https://lycos7560.com/wp-content/uploads/2023/02/image-90.png" alt="" class="wp-image-38367" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-90.png 1155w, https://lycos7560.com/wp-content/uploads/2023/02/image-90-300x198.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-90-768x507.png 768w" sizes="(max-width: 1155px) 100vw, 1155px" /></figure>



<figure class="wp-block-image size-full"><img decoding="async" width="1157" height="757" src="https://lycos7560.com/wp-content/uploads/2023/02/image-91.png" alt="" class="wp-image-38368" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-91.png 1157w, https://lycos7560.com/wp-content/uploads/2023/02/image-91-300x196.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-91-768x502.png 768w" sizes="(max-width: 1157px) 100vw, 1157px" /></figure>



<figure class="wp-block-image size-full"><img decoding="async" width="1154" height="720" src="https://lycos7560.com/wp-content/uploads/2023/02/image-92.png" alt="" class="wp-image-38369" srcset="https://lycos7560.com/wp-content/uploads/2023/02/image-92.png 1154w, https://lycos7560.com/wp-content/uploads/2023/02/image-92-300x187.png 300w, https://lycos7560.com/wp-content/uploads/2023/02/image-92-768x479.png 768w" sizes="(max-width: 1154px) 100vw, 1154px" /></figure>



<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-10217%eb%b2%88-kcm-travel-c-dijkstra-baekjoon/5982/">백준 10217번 (KCM Travel, C++, Dijkstra) [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-10217%eb%b2%88-kcm-travel-c-dijkstra-baekjoon/5982/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
