Barbara Bennett's Wild Numbers POJ - 3340(贪心)

A wild number is a string containing digits and question marks (like 36?1?8). A number X matches a wild number W if they have the same length, and every non-question mark character in X is equal to the character in the same position in W (it means that you can replace a question mark with any digit). For example, 365198 matches the wild number 36?1?8, but 360199, 361028, or 36128 does not. Write a program that reads a wild number W and a number X from input, both of length n, and determines the number of n-digit numbers that match W and are greater than X.

Input
There are multiple test cases in the input. Each test case consists of two lines of the same length. The first line contains a wild number W, and the second line contains an integer number X. The length of input lines is between 1 and 10 characters. The last line of input contains a single character #.

Output
For each test case, write a single line containing the number of n-digit numbers matching W and greater than X (n is the length of W and X).

Sample Input
36?1?8
236428
8?3
910
?
5

Sample Output
100
0
4

题意:
A:36?1?8
B:360199
求大于B且非问号位等于A的数字数目。
思路:
设问号为cnt个
从最高位比较。
不是问号:大于则为10cnt ,小于为0, 并退出。等于继续比较
是问号,加上10cnt-1 * (‘9’ - B[i]),并减去这个问号,继续向后比较。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;
char a[1005],b[1005];
ll t[20];
int main()
{
    t[0] = 1;
    for(int i = 1;i <= 18;i++)t[i] = t[i - 1] * 10;
    while(~scanf("%s",a))
    {
        if(a[0] == '#')
        {
            break;
        }
        scanf("%s",b);
        int len = (int)strlen(a);
        ll ans = 0;
        int cnt = 0;
        for(int i = 0;i < len;i++)
        {
            if(a[i] == '?')cnt++;
        }
        for(int i = 0;i < len;i++)
        {
            if(a[i] != '?')
            {
                if(a[i] > b[i])
                {
                    ans += t[cnt];
                    break;
                }
                else if(a[i] < b[i])
                    break;
            }
            else if(a[i] == '?')
            {
                cnt--;
                ans += t[cnt] * ('9' - b[i]);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

发布了628 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104055084