动态规划(dp)
一道京东的面试题,说下思路吧,其实很简单,从区间
[
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[j−ai]这里的
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;
}
新的开始,每天都要快乐哈!