SRM325 D2M RGBStreet

TopCoder Statistics - Problem Statement

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

家が横一列に並んでいて,まだ色がついてない.これを三色$RGB$に塗りたいが,隣り合う家が同じ色になってはいけない.家$i$を塗るコストは$R[i]$, $G[i]$, $B[i]$である.全体のコストを最小化したい.


$$ dp[i][j] := 家iを色jに塗る最小コスト $$ として動的計画法.$R, G, B$を$0, 1, 2$に対応させている.隣り合ってはいけないので遷移は以下のようになる.

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <queue>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define INF 1<<30
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int, int> P;

int dp[25][3];

vector<string> split(const string &str, char delim) {
  vector<string> res;
  size_t current = 0, found;
  while((found = str.find_first_of(delim, current)) != string::npos) {
      res.push_back(string(str, current, found - current));
      current = found + 1;
  }
  res.push_back(string(str, current, str.size() - current));
  return res;
}

int f(string s) {
  int ret;
  stringstream ss;
  ss << s;
  ss >> ret;
  return ret;
}

class RGBStreet {
  public:
  int estimateCost(vector <string> houses) {
      int n = houses.size();
      vector<int> R(n), G(n), B(n);
      rep(i, n) {
          vector<string> ret = split(houses[i], ' ');
          R[i] = f(ret[0]);
          G[i] = f(ret[1]);
          B[i] = f(ret[2]);
      }

      rep(i, 25) {
          rep(j, 3) dp[i][j] = INF;
      }

      rep(j, 3) {
          dp[0][j] = 0;
      }

      rep(i, n) {
          dp[i+1][0] = min(dp[i][1] + R[i], dp[i][2] + R[i]);
          dp[i+1][1] = min(dp[i][0] + G[i], dp[i][2] + G[i]);
          dp[i+1][2] = min(dp[i][0] + B[i], dp[i][1] + B[i]);
      }

      int ans = INF;
      rep(i, 3) {
          ans = min(ans, dp[n][i]);
      }

      return ans;
  }
};
Nov 18th, 2016