본문 바로가기

백준/DP

[USACO] 백준 5945 - Treasure Chest

728x90

참고

이 문제는 "동적계획법으로 푸는 게임이론" 문제이다. 이 키워드에 대해 잘 모르고 있다면 2040 - 수 게임 문제에 대한 풀이를 보고 오는 것이 이해에 도움이 된다.

 

링크 - https://nicotina04.tistory.com/272

 

백준 2040 - 수 게임

https://www.acmicpc.net/problem/2040 이 문제는 대단히 교육적인 문제이므로 꼭 공부하는 것을 추천한다. 게임 전략 A와 B 둘 다 최적으로 플레이를 한다고 했다. 이를 수식으로 표현하면 어떻게 될까? A의

nicotina04.tistory.com

풀이

두 명의 플레이어가 점수를 먹는 게임을 하므로 $max(First - Second)$를 구하는 문제가 된다.

 

게임 규칙은 단순하므로 $max(First - Second)$는 동적 계획법으로 어렵지 않게 계산할 수 있다.

 

하지만 문제에서 요구하는 것은 $max(First)$이다.

 

이때 $(First - Second) + sum = (First - Second) + (First + Second) = 2 First$이므로 $2 max(First)$가 답이 된다.

 

정답 코드 - C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// #pragma GCC target("fma,avx,avx2,bmi,bmi2,lzcnt,popcnt")
#pragma GCC optimize("O3,unroll-loops")
 
#include "bits/stdc++.h"
// #include "ext/pb_ds/assoc_container.hpp"
 
using namespace std;
// using namespace __gnu_pbds;
 
using ll = int_fast64_t;
using pii = pair<intint>;
// using oset = tree<int, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update>;
 
int n;
int ar[5001];
int dp[5001][5001];
 
int memo(int l, int r)
{
  if (l > r) return 0;
  auto &ret = dp[l][r];
  if (ret != -1e9return ret;
  int tmp = -1e9;
  tmp = max(tmp, ar[l] -memo(l + 1, r));
  tmp = max(tmp, ar[r] - memo(l, r - 1));
  return ret = tmp;
}
 
void solve()
{
  fill(&dp[0][0], &dp[0][0+ 5001 * 5001-1e9);
  cin >> n;
  int pref = 0;
  for (int i = 0; i < n; i++)
  {
    cin >> ar[i + 1];
    pref += ar[i + 1];
  }
  
  int val = memo(1, n);
  cout << (val + pref) / 2;
}
 
int main()
{
#ifdef LOCAL
  freopen("input.txt""r", stdin);
//  freopen("output.txt", "w", stdout);
#endif
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
 
  solve();
}
cs

 

 

 

 

728x90

'백준 > DP' 카테고리의 다른 글

백준 12199 - Password Attacker (Large)  (1) 2024.11.19
백준 23280 - 엔토피아의 기억 강화  (1) 2024.11.17
백준 32250 - Super Shy (Easy)  (0) 2024.11.11
백준 1398 - 동전 문제  (1) 2024.04.25
백준 2040 - 수 게임  (3) 2022.09.28