涂色PAINT
[CQOI2007]涂色PAINT
https://ac.nowcoder.com/acm/problem/19909
思路:用dp[i][j]表示从i到j涂好色的最少次数,从RGBGR这个样例我们可以发现,后面的颜色可以是前面就图好了,那么可以得当i,j相同时,这个i位置的颜色就是再涂区间i+1,j时涂好的,j位置是再涂区间i,j-1时涂好的dp[i][j]=min(dp[i+1][j],dp[i][j-1])。i,j不相同的时候,说明1次染色不行,分成2块去染枚举断点。dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j])
#include <cstdio> #include <cstring> #include <algorithm> #include <set> #include<iostream> #include<vector> #include<queue> //#include<bits/stdc++.h> using namespace std; typedef long long ll; #define SIS std::ios::sync_with_stdio(false) #define space putchar(' ') #define enter putchar('\n') #define lson root<<1 #define rson root<<1|1 typedef pair<int,int> PII; const int mod=1e9+7; const int N=2e6+10; const int M=1e5+10; const int inf=0x7f7f7f7f; const int maxx=2e5+7; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } ll lcm(ll a,ll b) { return a*(b/gcd(a,b)); } template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < '0' || c > '9') if(c == '-') op = 1; x = c - '0'; while(c = getchar(), c >= '0' && c <= '9') x = x * 10 + c - '0'; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar('0' + x % 10); } ll qsm(int a,int b,int p) { ll res=1%p; while(b) { if(b&1) res=res*a%p; a=1ll*a*a%p; b>>=1; } return res; } char s[N]; int dp[100][100]; int main() { scanf("%s",s+1); int n=strlen(s+1); memset(dp,inf,sizeof dp); for(int i=1;i<=n;i++)dp[i][i]=1; for(int len=2;len<=n;len++) { for(int i=1;i<=n;i++) { int j=i+len-1; if(j>n)break; if(s[i]==s[j]) dp[i][j]=min(dp[i-1][j],dp[i][j-1]); else for(int k=i;k<j;k++) dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]); } } printf("%d\n",dp[1][n]); return 0; } /* 1 3 2 1 1 2 3 4 1 0 1 2 3 2 1 2 3 4 */