mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-10-17 21:42:25 +00:00
feat: 添加P4170.cpp解决字符串最小染色问题
实现动态规划算法计算字符串的最小染色次数,用于解决P4170题目
This commit is contained in:
parent
c216681b80
commit
da0cc7208d
39
src/10/1/P4170.cpp
Normal file
39
src/10/1/P4170.cpp
Normal file
@ -0,0 +1,39 @@
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <string>
|
||||
using ll = int64_t;
|
||||
|
||||
const ll maxn=50+5,inf=1e9+7;
|
||||
std::string c;
|
||||
ll dp[maxn][maxn],n;
|
||||
|
||||
int main(){
|
||||
std::iostream::sync_with_stdio(false);
|
||||
std::cin.tie(nullptr);
|
||||
|
||||
std::cin>>c;
|
||||
n=c.size();
|
||||
c=' '+c;
|
||||
for(ll i=1;i<=n;i++){
|
||||
for(ll j=1;j<=n;j++){
|
||||
dp[i][j]=inf;
|
||||
}
|
||||
}
|
||||
for(ll i=0;i<=n;i++){
|
||||
dp[i][i]=1;
|
||||
}
|
||||
for(ll len=2;len<=n;len++){
|
||||
for(ll i=1;i+len-1<=n;i++){
|
||||
const ll j = i+len-1;
|
||||
for(ll k=i;k<j;k++){
|
||||
dp[i][j]=std::min(
|
||||
dp[i][j],
|
||||
dp[i][k]+dp[k+1][j]-(c[i]==c[j])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout<<dp[1][n]<<"\n";
|
||||
}
|
Loading…
Reference in New Issue
Block a user