[๋ฐฑ์ค c++] 1149 RGB๊ฑฐ๋ฆฌ (์ค1)
๐ ๋ฌธ์
RGB๊ฑฐ๋ฆฌ์๋ ์ง์ด N๊ฐ ์๋ค. ๊ฑฐ๋ฆฌ๋ ์ ๋ถ์ผ๋ก ๋ํ๋ผ ์ ์๊ณ , 1๋ฒ ์ง๋ถํฐ N๋ฒ ์ง์ด ์์๋๋ก ์๋ค.
์ง์ ๋นจ๊ฐ, ์ด๋ก, ํ๋ ์ค ํ๋์ ์์ผ๋ก ์น ํด์ผ ํ๋ค. ๊ฐ๊ฐ์ ์ง์ ๋นจ๊ฐ, ์ด๋ก, ํ๋์ผ๋ก ์น ํ๋ ๋น์ฉ์ด ์ฃผ์ด์ก์ ๋, ์๋ ๊ท์น์ ๋ง์กฑํ๋ฉด์ ๋ชจ๋ ์ง์ ์น ํ๋ ๋น์ฉ์ ์ต์๊ฐ์ ๊ตฌํด๋ณด์.
- 1๋ฒ ์ง์ ์์ 2๋ฒ ์ง์ ์๊ณผ ๊ฐ์ง ์์์ผ ํ๋ค.
- N๋ฒ ์ง์ ์์ N-1๋ฒ ์ง์ ์๊ณผ ๊ฐ์ง ์์์ผ ํ๋ค.
- i(2 ≤ i ≤ N-1)๋ฒ ์ง์ ์์ i-1๋ฒ, i+1๋ฒ ์ง์ ์๊ณผ ๊ฐ์ง ์์์ผ ํ๋ค.
์ฒ์์ ์ด ๋ฌธ์ ๋ฅผ DFS๋ก ํ์๋ค. ํ๋ฆฐ๋ค... ํ์ง๋ง ์๊ฐ์ด๊ณผ... ์์ผ๊น ๊ณ ๋ฏผํด๋ดค๋ค
#include <iostream>
using namespace std;
int MIN = 999000;
int N;
int Red[1001];
int Green[1001];
int Blue[1001];
//DP๋ก ์ด์ ๊ฐ ์ ์ฅ
int total[1001][3];
//DFS search
void Search(int Before, int idx){
//๋์ผ ๊ฒฝ์ฐ
if(idx == N){
if(MIN > total[idx -1][Before]) MIN = total[idx -1][Before];
return;
}
//์์ด Red์ผ ๊ฒฝ์ฐ
if(Before == 0){
//Green ์์น
total[idx][1] = total[idx-1][Before] + Green[idx];
Search(1, idx + 1);
//Blue ์์น
total[idx][2] = total[idx-1][Before] + Blue[idx];
Search(2, idx + 1);
}
//์์ด Green์ผ ๊ฒฝ์ฐ
else if(Before == 1){
//Red ์์น
total[idx][0] = total[idx-1][Before] + Red[idx];
Search(0, idx + 1);
//Blue ์์น
total[idx][2] = total[idx-1][Before] + Blue[idx];
Search(2, idx + 1);
}
//์์ด Blue์ผ ๊ฒฝ์ฐ
else if(Before == 2){
//Red ์์น
total[idx][0] = total[idx-1][Before] + Red[idx];
Search(0, idx + 1);
//Green ์์น
total[idx][1] = total[idx-1][Before] + Green[idx];
Search(1, idx + 1);
}
}
int main()
{
cin >> N;
for(int i = 0; i < N; i++) cin >> Red[i] >> Green[i] >> Blue[i];
total[0][0] = Red[0];
total[0][1] = Green[0];
total[0][2] = Blue[0];
//search
Search(0,1);
Search(1,1);
Search(2,1);
//output
cout << MIN << endl;
return 0;
}
๋ฌธ์ ์ ์ฝ๋์ธ๋ฐ DFS ์ฝ๋๊ฐ ์ต์ ํ๊ฐ ์ ๋์ด ์๋๊ฐ? ๊ณ์ ์์ ํด๋ดค์ง๋ง ์๋ฌด๋ฆฌ ์๊ฐํด๋ ์ ์ ์๋ค ์ผ์ !
But, ์๊ฐ๋ณต์ก๋๋ฅผ ์๊ฐํด๋ณด์.
์ฒซ๋ฒ์งธ ์ง์ ์ ํํ ์ ์๋ ์ง์ 3๊ฐ๊ณ ๊ทธ ์ดํ 2~N๊น์ง์ ์ง์ ์ด 2๊ฐ์ ์ ํ์ง๊ฐ ์์ผ๋ฏ๋ก,
์๊ฐ๋ณต์ก๋๋ 3 X 2^(N-1) => O(2^N)...
๋นํจ์จ์ ์ธ ๋ฐฉ๋ฒ์์ ๊นจ๋ฌ์๋ค... ์ด๋ฐใ
์ด ๋ฌธ์ ๋ DP๋ก ํ ์ ์๋ค.. DP๋ก ์ด์ ์ ์ต์๊ฐ์ ๋ฐฐ์ด์ ์ ์ฅํ๊ณ ์ด๋ฅผ ๊ณ์ ์ ์ฅํด๋๊ฐ๋ ์์ ์ ๋ฐ๋ณตํ๋ฉด
N๋ฐํด๋ง ํ์์ ํ๋ฉด๋๊ธฐ ๋๋ฌธ์ ์๊ฐ๋ณต์ก๋๋ O(N)์ด๋ค.. ์ด๋ด์๊ฐ...
์ด๋์ ์๊ฐ๋ณต์ก๋๋ฅผ ๋ฏธ๋ฆฌ ์๊ฐํด๋ณด๊ณ ๋ฌธ์ ๋ฅผ ํธ๋ ๊ฒ์ด ์ค์ํ๋ค
๐ป ์ ๋ต ์ฝ๋
#include <iostream>
using namespace std;
int MIN;
int N;
int Red[1001];
int Green[1001];
int Blue[1001];
//DP๋ก ์ด์ ๊ฐ ์ ์ฅ
int total[1001][3];
int main()
{
cin >> N;
for(int i = 0; i < N; i++) cin >> Red[i] >> Green[i] >> Blue[i];
total[0][0] = Red[0];
total[0][1] = Green[0];
total[0][2] = Blue[0];
//search
for(int i = 1; i < N; i++){
total[i][0] = total[i-1][1] < total[i-1][2] ? total[i-1][1] : total[i-1][2];
total[i][0] += Red[i];
total[i][1] = total[i-1][0] < total[i-1][2] ? total[i-1][0] : total[i-1][2];
total[i][1] += Green[i];
total[i][2] = total[i-1][0] < total[i-1][1] ? total[i-1][0] : total[i-1][1];
total[i][2] += Blue[i];
}
MIN = total[N-1][0] < total[N-1][1] ? total[N-1][0] : total[N-1][1];
MIN = total[N-1][2] < MIN ? total[N-1][2] : MIN;
//output
cout << MIN << endl;
return 0;
}