HDU 6103 Kirinriki 【dp】

Kirinriki

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1275    Accepted Submission(s): 503


Problem Description
We define the distance of two strings A and B with same length n is
disA,B=i=0n1|AiBn1i|
The difference between the two characters is defined as the difference in ASCII.
You should find the maximum length of two non-overlapping substrings in given string S, and the distance between them are less then or equal to m.
 

Input
The first line of the input gives the number of test cases T; T test cases follow.
Each case begins with one line with one integers m : the limit distance of substring.
Then a string S follow.

Limits
T100
0m5000
Each character in the string is lowercase letter,  2|S|5000
|S|20000
 

Output
For each test case output one interge denotes the answer : the maximum length of the substring.
 

Sample Input
  
  
1 5 abcdefedcb
 

Sample Output
  
  
5
Hint
[0, 4] abcde [5, 9] fedcb The distance between them is abs('a' - 'b') + abs('b' - 'c') + abs('c' - 'd') + abs('d' - 'e') + abs('e' - 'f') = 5
 

Source
 
转自:http://blog.youkuaiyun.com/qq_37412229/article/details/77073094

思路:假设i是左边s1串的头位置,j是右边s2串尾位置,那么状态转移的方程不就是看abs(str[j]-str[i])+ len[i+1][j-1])是否小于等于m(len[i][j]表示这俩个串所能组成最长子串的花费是多少),如果是直接 dp[i][j] = dp[i+1][j-1] + 1,否则要逐步的去将上一个状态的长度末尾删去直到满足<=m为止.因为只有俩个状态所以开2就够了,内存问题根本不用担心。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
#define ll long long
#define ms(a,b)  memset(a,b,sizeof(a))
#define maxn 510
const int M=1e6+10;
const int MM=2e3+10;
const int inf=0x3f3f3f3f;
const int mod=998244353;
const double eps=1e-10;
int n,m,k;
int len[2][M],dp[2][M];
char str[M];

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        ms(len,0);
        ms(dp,0);
        scanf("%d%s",&m,str+1);
        int lens=strlen(str+1);
        int id=1,ans=0;
        for(int i=lens;i>=1;i--,id^=1)
        for(int j=i+1;j<=lens;j++){
            int u=abs(str[j]-str[i]);
            if(u>m){
                dp[id][j]=0;len[id][j]=u;
                continue;
            }
            if(len[id^1][j-1]+u<=m)
                dp[id][j]=dp[id^1][j-1]+1,len[id][j]=len[id^1][j-1]+u;
            else {
                int val=len[id^1][j-1],l=dp[id^1][j-1];
                while(u+val>m&&l){
                    val-=abs(str[i+l]-str[j-l]);
                    l--;
                }
                dp[id][j]=l+1,len[id][j]=u+val>m?u:u+val;
            }
            ans=max(ans,dp[id][j]);
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值