[문제풀이] CF1107 E: Vasya and Binary String

본제 전송문령 dpi, j, kdp{i,j,k}dpi,j,k는 구간 [i,j],j[i,j],j[i,j],j의 오른쪽에서 kk개를 함께 삭제할 수 있음
  • d p i , j , k = m a x ( d p i , j − 1 , 0 + a k + 1 ) dp_{i,j,k}=max(dp_{i,j-1,0}+a_{k+1}) dpi,j,k​=max(dpi,j−1,0​+ak+1​)
  • d p i , j , t = m a x ( d p k + 1 , j − 1 , 0 + d p i , k , t + 1 ( s k = s j ) ) dp_{i,j,t}=max(dp_{k+1,j-1,0}+dp_{i,k,t+1}(s_k=s_j)) dpi,j,t​=max(dpk+1,j−1,0​+dpi,k,t+1​(sk​=sj​))

  • O(n3)O(n^3)O(n3)개 상태, 각 상태마다 O(n)O(n)O(n)O(n)회 코드:
    #include 
    #define maxn 110
    #define LL long long
    using namespace std;
    char s[maxn];
    int n;
    LL a[maxn], dp[maxn][maxn][maxn], sum[maxn];
    
    inline int read(){
    	int s = 0, w = 1;
    	char c = getchar();
    	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
    	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
    	return s * w;
    }
    
    int main(){
    	n = read();
    	scanf("%s", s + 1);
    	for (int i = 1; i <= n; ++i){
    		a[i] = read();
    		for (int j = 1; j < i; ++j) a[i] = max(a[i], a[j] + a[i - j]);
    	}
    	for (int i = 1; i <= n; ++i)
    		for (int j = i + 1; j <= n; ++j) sum[i] += (s[i] == s[j]);
    	for (int i = n; i; --i)
    		for (int j = i; j <= n; ++j){
    			for (int k = 0; k <= sum[j]; ++k) dp[i][j][k] = max(dp[i][j][k], dp[i][j - 1][0] + a[k + 1]);
    			for (int k = i; k < j; ++k) if (s[k] == s[j])
    				for (int t = 0; t <= sum[j]; ++t) dp[i][j][t] = max(dp[i][j][t], dp[k + 1][j - 1][0] + dp[i][k][t + 1]);
    		}
    	printf("%lld
    "
    , dp[1][n][0]); return 0; }

    좋은 웹페이지 즐겨찾기