ZOJ 3816 Generalized Palindromic Number

Generalized Palindromic Number

Time Limit: 2 Seconds       Memory Limit: 65536 KB

A number that will be the same when it is written forwards or backwards is known as a palindromic number. For example, 1234321 is a palindromic number.

We call a number generalized palindromic number, if after merging all the consecutive same digits, the resulting number is a palindromic number. For example, 122111 is a generalized palindromic number. Because after merging, 122111 turns into 121 which is a palindromic number.

Now you are given a positive integer N, please find the largest generalized palindromic number less than N.

Input

There are multiple test cases. The first line of input contains an integer T (about 5000) indicating the number of test cases. For each test case:

There is only one integer N (1 <= N <= 1018).

Output

For each test case, output the largest generalized palindromic number less than N.

Sample Input
4
12
123
1224
1122
Sample Output
11
121
1221

1121

题意:给出一个数n,求小于n的一个最大的广义回文数。

搜索学的不够啊!写了好久

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#define ll long long
using namespace std;
const int maxn=100;

int num[maxn],cnt,le[maxn],ri[maxn];
ll n;

ll get_num(int l,int r)
{
    ll ret=0;
    for(int i=0;i<l;i++)  ret=ret*10+le[i];
    for(int i=r;i>=1;i--)  ret=ret*10+ri[i];
    return ret;
}

ll dfs(int l,int r,bool flag)
{
    ll ans=-1;
    if(l+r>cnt) return -1;
    if(l+r==cnt)
    {
        ans=get_num(l,r);
        if(ans>=n) return -1;
       // cout<<ans<<endl;
        return ans;
    }
    int m=flag ? num[l]:9;
    for(int i=m;i>=0;i--)
    {
        le[l]=i;
        if((l==0 || le[l]!=le[l-1]) && (l!=0 || i!=0) && (l+r+1!=cnt))
        {
             for(int j=1;j+l+r+1<=cnt;j++)
             {
                  ri[r+j]=i;
                  ans=max(ans,dfs(l+1,r+j,flag && (i==m)));
             }
        }
        else  ans=max(ans,dfs(l+1,r,flag && (i==m)));
        if(ans>0)  return ans;
    }
    return ans;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld",&n);
        cnt=0;
        ll tp=n;
        while(tp)
        {
            num[cnt++]=tp%10;
            tp=tp/10;
        }
        reverse(num,num+cnt);
        printf("%lld\n",dfs(0,0,1));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值