Matches
We can make digits with matches as shown below:
![ACM: <wbr>uva <wbr>11375 <wbr>- <wbr>Matches ACM: <wbr>uva <wbr>11375 <wbr>- <wbr>Matches](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
Given N matches, find the number of different numbers representable using the matches. We shall only make numbers greater than or equal to 0, so no negative signs should be used. For instance, if you have 3 matches, then you can only make the numbers 1 or 7. If you have 4 matches, then you can make the numbers 1, 4, 7 or 11. Note that leading zeros are not allowed (e.g. 001, 042, etc. are illegal). Numbers such as 0, 20, 101 etc. are permitted, though.
Input contains no more than 100 lines. Each line contains one integer N (1 ≤ N ≤ 2000).
For each N, output the number of different (non-negative) numbers representable if you have Nmatches.
3
4
2
4
题意: 给你n根matches, 你可以拼出多少个数字0~9. 不必全部用完.
解题思路:
1. 计数题, 本题可以用图来理解. 把"已经使用了i根matches"看成状态, 这样就可以得到一个图.
每次从前往后在添加一个数字x时, 状态就从i变成i+c[x](c[x]拼x需要多少根matches);
2. 有了上面的基础, 可以得到状态方程: dp[i+c[x]] += dp[i];(dp[i]就是从0到节点i的路径数目)
那么结果是: dp[1]+dp[2]+...+dp[n](因为matches不必全部用完, 加法原理);
3. 最后要注意的是前导0是不允许的, 所以当n>=6的时候全部要加上1;
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
#define MAX 2011
inline int max(int a, int b)
{
return a > b ? a : b;
}
struct bign
{
//初始化.
int len, s[MAX];
bign() { memset(s,0,sizeof(s)); len = 1; }
bign(int num) { *this = num; }
bign(const char *num) { *this = num; }
bign operator= (const char *num)
{
len = strlen(num);
for(int i = 0; i < len; ++i)
s[i] = num[len-i-1] - '0';
return *this;
}
bign operator= (int num)
{
char str[MAX];
sprintf(str,"%d",num);
*this = str;
return *this;
}
//辅助函数
void clean() { while(len > 1 && !s[len-1]) len--; }
string str() const
{
string res = "";
for(int i = 0; i < len; ++i)
res = (char)(s[i] + '0') + res;
if(res == "") res = "0";
return res;
}
//加减乘除
bign operator+ (const bign &b) const
{
bign c;
c.len = 0;
for(int i = 0,g = 0; g || i < max(len,b.len); ++i)
{
int x = s[i] + b.s[i] + g;
c.s[c.len++] = x % 10;
g = x / 10;
}
c.clean();
return c;
}
bign operator+= (const bign &b)
{
*this = *this + b;
return *this;
}
};
istream & operator>> (istream &in,bign &x)
{
string s;
in >> s;
x = s.c_str();
return in;
}
ostream & operator<< (ostream &out,const bign &x)
{
out << x.str();
return out;
}
int n;
int c[12] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
bign dp[MAX];
void init()
{
bign one;
one = 1;
int i, j;
for(i = 1; i < 10; ++i)
dp[ c[i] ] += one;
for(i = 1; i <= 2000; ++i)
for(j = 0; j < 10; ++j)
dp[i+c[j]] += dp[i];
dp[6] += one;
for(i = 1; i <= 2000; ++i)
dp[i] += dp[i-1];
}
int main()
{
// freopen("input.txt", "r", stdin);
init();
while(scanf("%d", &n) != EOF)
{
cout << dp[n] << endl;
}
return 0;
}