CodeForces 607B zuma
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?
Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones.
The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.
Output
Print a single integer — the minimum number of seconds needed to destroy the entire line.
Examples
3
1 2 1
1
3
1 2 3
3
7
1 4 4 2 3 2 1
2
Note
In the first sample, Genos can destroy the entire line in one second.
In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.
In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
题解:题解:区间DP。若区间i~j为回文串,那么i+1~j-1也必然为回文串,dp[i][j]=dp[i+1][j-1],
如果不是,这就枚举中间点,区间DP裸题;
参考代码为:

1 #include<bits/stdc++.h> 2 using namespace std; 3 4 int num[550], dp[550][550]; 5 int main() 6 { 7 int n; 8 while (~scanf("%d", &n)) 9 { 10 memset(num, 0, sizeof(num)); 11 memset(dp,0x3f,sizeof(dp)); 12 for (int i = 1; i <= n; i++) 13 scanf("%d", &num[i]); 14 for (int i = 1; i <= n; i++) 15 dp[i][i] = 1; 16 for (int i = n; i >= 1; i--) 17 for (int j = i + 1; j <= n; j++) 18 { 19 if (num[i] == num[j]) 20 { 21 if (abs(j - i) != 1) 22 dp[i][j] = dp[i + 1][j - 1]; 23 else 24 dp[i][j] = 1; 25 } 26 27 for (int k = i; k<j; k++) 28 { 29 dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); 30 } 31 } 32 printf("%d\n", dp[1][n]); 33 } 34 return 0; 35 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?