dp

动态规划(dp)

题目:
https://www.nowcoder.com/practice/56d818ae68134c12b26e81f41ecafb9e?tpId=90&tqId=30841&tPage=4&rp=4&ru=/ta/2018test&qru=/ta/2018test/question-ranking

一道京东的面试题,说下思路吧,其实很简单,从区间 [ l , r ] [l,r] [l,r]依次枚举每个数,然后计算他们的数位和 s u m sum sum, 因为是要分成两组相等,所以 s u m sum sum为奇数的情况显然可以排除,那么偶数的时候只要 d p dp dp一下就好了, 这个关系式可以写成:
d p [ j ] = d p [ j − a i ] dp[j]=dp[j-a_i] dp[j]=dp[jai]这里的 a i a_i ai指的是这个数的每个数位,然后只要知道答案 d p [ s u m 2 ] dp[\frac{sum}{2}] dp[2sum]是否为0就行了。这个复杂度算起来其实蛮大的,不过和为奇数的情况蛮多的,所以最后还是AC了(hehehe).

AC代码:

//  小学生一发的刷题之路
//
//  Mannacher Algorithm
//
//

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <deque>                //双向队列;
#include <cmath>
#include <set>
#include <stack>
#include <map>
#include <vector>
#include <cstdlib>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double PI=acos(-1.0);
const double eps=1e-8;
const int maxn=1e3+5;
const int maxm=1e3+5;
const ll mod=1e9+7;
const int INF=1e8;
template<class T>
inline void read(T &ret){       //快速输入模版;
    ret=0;
    int f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        ret=ret*10+c-'0';
        c=getchar();
    }
    ret*=f;
}
template <class T>
inline void out(T ret){     //快速输出模版;
    if(ret>9)
    {
        out(ret/10);
    }
    putchar(ret%10+'0');
}
int l,r,a[20],dp[100];

bool pd(int x){
    int n=0,sum=0;
    while(x>0){
        a[++n]=x%10;
        sum+=a[n];
        x/=10;
    }
    if(sum%2){          //和为奇数时;
        return false;
    }
    
    //dp[j]表示和为j的方法数;
    memset(dp,0,sizeof(dp));
    dp[0]=1;
    for(int i=1;i<=n;i++)
        for(int j=sum/2;j>=a[i];j--){
            dp[j]+=dp[j-a[i]];
        }
    
    return dp[sum/2]>0;
}

int main()
{
    scanf("%d %d",&l,&r);
    int ans=0;
    for(int i=l;i<=r;i++){
        if(pd(i)){
            ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}

新的开始,每天都要快乐哈!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值