uva10453(回文串dp)

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
inline int Readint(){
	char c = getchar();
	while(!isdigit(c)) c = getchar();
	int x = 0;
	while(isdigit(c)){
		x = x * 10 + c - '0';
		c = getchar();
	}
	return x;
}
char s[1010];
int rec[1010][1010],dp[1010][1010];
int cnt;
void solve(int l,int r)
{
	if (l > r) return;
	if (l == r) printf("%c",s[l]);
	else{
		if (rec[l][r] == 0){
			printf("%c",s[l]);
			solve(l + 1,r - 1);
			printf("%c",s[l]);
		}else if (rec[l][r] == 1){
			printf("%c",s[r]);
			solve(l,r - 1);
			printf("%c",s[r]);
		}else{
			printf("%c",s[l]);
			solve(l + 1,r);
			printf("%c",s[l]);
		}
	}
}


int main()
{	
	freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	while(scanf("%s",s) != EOF){
		memset(dp, 0,sizeof dp);
		memset(rec, 0,sizeof rec);
		int len = strlen(s);
		cnt = 0;
		for (int i = len - 1;i >= 0;--i){
			for (int j = i + 1;j < len;++j){
				if (s[i] == s[j]) {
					dp[i][j] = dp[i + 1][j - 1];
				}
				else{ 
					if (dp[i + 1][j] > dp[i][j - 1]){
						dp[i][j] = dp[i][j - 1] + 1;
						rec[i][j] = 1;
					}
					else {
						dp[i][j] = dp[i + 1][j] + 1;
						rec[i][j] = -1;
					}
				}
			}
		}
		printf("%d ",dp[0][len - 1]);
		solve(0,len - 1);
		printf("\n");
	}
	return 0;
}

你可能感兴趣的:(String,基础dp)