๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

16198๋ฒˆ: ์—๋„ˆ์ง€ ๋ชจ์œผ๊ธฐ

N๊ฐœ์˜ ์—๋„ˆ์ง€ ๊ตฌ์Šฌ์ด ์ผ๋ ฌ๋กœ ๋†“์—ฌ์ ธ ์žˆ๊ณ , ์—๋„ˆ์ง€ ๊ตฌ์Šฌ์„ ์ด์šฉํ•ด์„œ ์—๋„ˆ์ง€๋ฅผ ๋ชจ์œผ๋ ค๊ณ  ํ•œ๋‹ค. i๋ฒˆ์งธ ์—๋„ˆ์ง€ ๊ตฌ์Šฌ์˜ ๋ฌด๊ฒŒ๋Š” Wi์ด๊ณ , ์—๋„ˆ์ง€๋ฅผ ๋ชจ์œผ๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, ๋ฐ˜๋ณตํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ

www.acmicpc.net

 

๐Ÿง‘๐Ÿป‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

  1. ์—๋„ˆ์ง€ ๊ฐ’๋“ค์„ 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 ๊ฐ’๊ณผ ํ•จ๊ป˜ ์žฌ๊ท€๋กœ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.
  2. weights.size() == 2๊ฐ€ ๋˜์—ˆ๋‹ค๋ฉด, maxEnegy = max(maxEnegy, sum)์œผ๋กœ ๊ฐฑ์‹ ํ•ฉ๋‹ˆ๋‹ค.
  3. ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋˜์—ˆ๋‹ค๋ฉด, ๋‹ต์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#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
๋ฐ˜์‘ํ˜•