也是数位dp。考虑反面会简单很多。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,dp[30][30][30],ret=0,bit[11]; void get_bit(int x) { ret=0; while (x) {bit[++ret]=x%10;x/=10;} } int dfs(int pos,int mod,int flag1,bool flag2) { if (!pos) return !mod; if ((!flag2) && (~dp[pos][mod][flag1])) return dp[pos][mod][flag1]; int ans=0,up=flag2?bit[pos]:9,lim=flag1?3:-1; for (int i=0;i<=up;i++) { if (i==lim) continue; ans+=dfs(pos-1,(mod*10+i)%13,(i==1),flag2&&i==up); } if (!flag2) dp[pos][mod][flag1]=ans; return ans; } int main() { memset(dp,-1,sizeof(dp)); while (scanf("%d",&n)!=EOF) { get_bit(n); printf("%d ",n/13-dfs(ret,0,0,1)+1); } return 0; }