UVA11584---区间DP

传送门

实现代码

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 1e3;
const int inf = 0x3f3f3f3f;
bool isPaline[maxn][maxn];
int cnt[maxn];

int count(string str) {
	int len = str.length();
	memset(isPaline, false, sizeof(isPaline));
	memset(cnt, inf, sizeof(cnt));
	for (int i = 0; i < len; i++) {
		for (int j = i; j >= 0; j--) {
			if ( j == i || (str[j] == str[i] && (i == j + 1 || isPaline[j + 1][i - 1]))) {
				isPaline[j][i] = true;
				if (j == 0) cnt[i] = 1; // 说明i前所有都可以融进一个回文串
				else if (cnt[j - 1] + 1 < cnt[i]) cnt[i] = cnt[j - 1] + 1; // 算 新回文串前有多少个 + 新增这个
			}
		}
	}
	return cnt[len - 1];
}


int main() {
	int n;
	string str;
	cin >> n;
	while (n--) {
		cin >> str;
		cout << count(str) << endl;
	}
	return 0;
}
发布了160 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44778155/article/details/105498448