728x90
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ป๐ปํ์ด ๊ณผ์
- ์๋์ง ๊ฐ๋ค์ vector<int> weights์ ์ ์ฅํ ํ, weights์ ํฌ๊ธฐ๊ฐ 2๊ฐ ๋ ๋๊น์ง ๋ค์ ๊ณผ์ ์ ๋ฐ๋ณตํฉ๋๋ค.
- ์ ๋ต์ ์ ์ฅํ ๋ณ์(maxEnegy)์ ํ์ฌ ๊ฒฝ์ฐ์ ์์ ํฉ๊ณ๋ฅผ ์ ์ฅํ ๋ณ์(sum)๋ฅผ ์์ฑํฉ๋๋ค.
- weights๋ฅผ i = 1๋ถํฐ i = weights.size() - 1๊น์ง for ๋ฌธ์ผ๋ก ์ํํฉ๋๋ค.
- weights[i - 1] x weights[i + 1]์ ๊ฐ์ sum์ ๋ํฉ๋๋ค.
- weights[i] ์์๋ ์ญ์ ํฉ๋๋ค.
- ๋ํด์ง sum ๊ฐ๊ณผ ํจ๊ป ์ฌ๊ท๋ก ํธ์ถํฉ๋๋ค.
- weights.size() == 2๊ฐ ๋์๋ค๋ฉด, maxEnegy = max(maxEnegy, sum)์ผ๋ก ๊ฐฑ์ ํฉ๋๋ค.
- ํจ์๊ฐ ์ข ๋ฃ๋์๋ค๋ฉด, ๋ต์ ์ถ๋ ฅํฉ๋๋ค.
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <iostream>
#include <vector>
using namespace std;
void Backtracking(vector<int>& weights, int& maxEnegy, int sum)
{
if (weights.size() == 2)
{
maxEnegy = max(maxEnegy, sum);
return;
}
for (int i = 1; i < weights.size() - 1; i++)
{
int element = weights[i];
int addValue = weights[i - 1] * weights[i + 1];
weights.erase(weights.begin() + i);
Backtracking(weights, maxEnegy, sum + addValue);
weights.emplace(weights.begin() + i, element);
}
}
int GetMaxEnegy(vector<int>& weights)
{
int answer = -1;
Backtracking(weights, answer, 0);
return answer;
}
int main()
{
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int N;
cin >> N;
vector<int> weights(N);
for (int i = 0; i < N; i++)
cin >> weights[i];
int answer = GetMaxEnegy(weights);
cout << answer;
return 0;
}
728x90
๋ฐ์ํ
'๐คAlgorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 10844๋ฒ | ์ฌ์ด ๊ณ๋จ ์ (C++) (0) | 2023.08.26 |
---|---|
[BOJ] 3190๋ฒ | ๋ฑ (C++) (1) | 2023.08.26 |
[BOJ] 1759๋ฒ | ์ํธ ๋ง๋ค๊ธฐ (C++) (0) | 2023.08.25 |
[BOJ] 15686๋ฒ | ์นํจ ๋ฐฐ๋ฌ (C++) (0) | 2023.08.24 |
[BOJ] 1309๋ฒ | ๋๋ฌผ์ (C++) (0) | 2023.08.24 |