백준2449 전구

문제 링크

  • http://icpc.me/2449

문제 출처

  • 2100 KOI 초등부 4번

사용 알고리즘

  • DP

시간복잡도

  • O(N3)

풀이

dp[s][e] = [s, e]구간을 같은 색으로 만드는 데 필요한 횟수로 정의하고 N^3 DP를 돌려주면 됩니다.

전체 코드

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
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define x first
#define y second
#define all(v) v.begin(), v.end()
#define compress(v) sort(all(v)), v.erase(unique(all(v)), v.end())
using namespace std;
//using namespace __gnu_pbds;

typedef long long ll;
typedef pair<ll, ll> p;
//typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

ll gcd(ll x, ll y) { return y ? gcd(y, x%y) : x; }
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }
ll mod(ll a, ll b) { return ((a%b) + b) % b; }
ll ext_gcd(ll a, ll b, ll &x, ll &y) { //ax + by = gcd(a, b)
  ll g = a; x = 1, y = 0;
  if (b) g = ext_gcd(b, a % b, y, x), y -= a / b * x;
  return g;
}
ll inv(ll a, ll m){ //ax mod m = 1
    ll x, y;
    ll g = ext_gcd(a, m, x, y);
    if(g > 1) return -1;
    return mod(x, m);
}

int n, k;
int arr[222];
int dp[222][222];

int f(int s, int e){
	int &res = dp[s][e];
	if(res != -1) return res;
	if(s == e) return res = 0;
	res = 1e9+7;
	for(int i=s; i<e; i++){
		int t = arr[s] != arr[i+1];
		res = min(res, f(s, i) + f(i+1, e) + t);
	}
	return res;
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin >> n >> k;
	memset(dp, -1, sizeof dp);
	for(int i=1; i<=n; i++) cin >> arr[i];
	cout << f(1, n);
}