Tuesday, July 29, 2008

Ugly Numbers

Problem

Once upon a time in a strange situation, people called a number ugly if it was divisible by any of the one-digit primes (2, 3, 5 or 7). Thus, 14 is ugly, but 13 is fine. 39 is ugly, but 121 is not. Note that 0 is ugly. Also note that negative numbers can also be ugly; -14 and -39 are examples of such numbers.

One day on your free time, you are gazing at a string of digits, something like:


123456
You are amused by how many possibilities there are if you are allowed to insert plus or minus signs between the digits. For example you can make 1 + 234 - 5 + 6 = 236
which is ugly. Or 123 + 4 - 56 = 71
which is not ugly.

It is easy to count the number of different ways you can play with the digits: Between each two adjacent digits you may choose put a plus sign, a minus sign, or nothing. Therefore, if you start with D digits there are 3D-1 expressions you can make.

Note that it is fine to have leading zeros for a number. If the string is "01023", then "01023", "0+1-02+3" and "01-023" are legal expressions.

Your task is simple: Among the 3D-1 expressions, count how many of them evaluate to an ugly number.

Input

The first line of the input file contains the number of cases, N. Each test case will be a single line containing a non-empty string of decimal digits.

Output

For each test case, you should output a line


Case #X: Ywhere X is the case number, starting from 1, and Y is the number of expressions that evaluate to an ugly number.
Limits

0 <= N <= 100.

The string in each test case will be non-empty and will contain only characters '0' through '9'.

Small dataset

Each string is no more than 13 characters long.

Large dataset

Each string is no more than 40 characters long.

Sample


Input

Output

4
1
9
011
12345

Case #1: 0
Case #2: 1
Case #3: 6
Case #4: 64






#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;

ifstream fin("input.txt");
ofstream fout("output.txt");

long long CalcNum(string str){
long long res=0;
for (int i=0;i<str.size();i++){
res=res*10+str[i]-'0';
res%=210;
}
return res;
}

int main(){
int N,Test;
unsigned long long d[41][210];
fin>>N;
for (int Test=1;Test<=N;Test++){
string str;
fin>>str;
memset(d,0,sizeof(d));
d[0][0]=1;
for (int i=1;i<=str.size();i++){
for (int j=0;j<i;j++){
for (long long k=0;k<210;k++){
if (d[j][k]==0) continue;
long long x=k+CalcNum(str.substr(j,i-j));
x%=210;
d[i][x]+=d[j][k];
if (j==0) continue;
x=k-CalcNum(str.substr(j,i-j));
x%=210;
if (x<0) x+=210;
d[i][x]+=d[j][k];
}
}
}
unsigned long long res=0;
for (int i=0;i<210;i++){
if (i%2==0||i%3==0||i%5==0||i%7==0){
res+=d[str.size()][i];
}
}
fout<<"Case #"<<Test<<": "<<res<<endl;
}
fout.close();
return 0;
}

6 comments:

misan said...

I could use some help for understanding your code. I can see what it does and why you use 210 but not so sure about the loops. Could you please elaborate a bit on your solution?

Thanks,

Miguel

任腾的blog said...

You know, the algorithm of this problem is dynamic programming.

The state called d[l][m] means how many ways which the first l-numbers construct a sum of module 210 is m.

Then the state transition equation is d[l][m]=sum{d[x][y],x<l,(y+-substr(x,l-x+1))%210==m}.

210 means 2*3*5*7. You know the states is circulating by every 210.

Nabil Shams said...

Hi,
I have checked your post about the ugly number problem at Google Code Jam. Would it be possible for you to explain it in more detail because I am unable to get the crux behind it. May be a one page description would be handful and would help in understanding this problem.

任腾的blog said...

If you know how many ways of first k-length numbers could construct the numbers which module 210 is m, then you could recurrence the next value.

The thought is dynamic programming (DP), if you first hit such problem, I suggest you to do some easy DP problem, for example @USACO(http://ace.delos.com/usacogate)

Nabil Shams said...

I want you to look into my code, it's working fine but as I have told that it is taking too much of time.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SRM.Application
{

class Program
{
private static long count = 0;
static void evaluate(string exp)
{
string[] numbers = exp.Split(new char[] {'+','-'});
string[] operators = exp.Split(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });

int index = 0;
long value = long.Parse(numbers[0]);
for (int i = 0; i < operators.Length; i++)
{
if (operators[i] == "+")
value += long.Parse(numbers[index++ + 1]);
else if (operators[i] == "-")
value -= long.Parse(numbers[index++ + 1]);
}
if (value % 2 == 0 || value % 3 == 0 || value % 5 == 0 || value % 7 == 0)
count++;


}
static void createExpression(string prefix, string postfix, int times)
{
if ( times == 0)
{
//Console.WriteLine("{0}{1}", prefix, postfix);
evaluate(prefix + postfix);
}
for (int i = 1; i < postfix.Length; i++)
{
string plus = "+";
string minus = "-";
createExpression(prefix + postfix.Substring(0, i) + plus, postfix.Substring(i, postfix.Length - i), times - 1);
createExpression(prefix + postfix.Substring(0, i) + minus, postfix.Substring(i, postfix.Length - i), times - 1);
}
}
static void Main(string[] args)
{
StreamReader reader = new StreamReader("B-large.in");
StreamWriter writer = new StreamWriter("B-large.out");
int testcases = int.Parse(reader.ReadLine());

DateTime time = DateTime.Now;
for (int nCase = 0; nCase < testcases; nCase++)
{
string str = reader.ReadLine();
for (int i = 0; i < str.Length; i++)
{
createExpression("", str, i);
}
//writer.WriteLine("Case #{0}: {1}", nCase+1, count);
//writer.Flush();
Console.WriteLine("Case #{0}: {1}", nCase + 1, count);
count = 0;
}

TimeSpan timespan = DateTime.Now - time;
Console.WriteLine("{0}:{1}:{2}", time.Minute, time.Second, time.Millisecond);

}
}
}

任腾的blog said...

I know, your solution is brute force, you make all the `3^(L-1)` possible ways, and judge it whether a ugly number. But the better algorithm is Dynamic Programming as I mentioned before.

I still suggest you to do some easy DP problem or reading some meterial about the thought.

see that:
http://hi.baidu.com/vincentz/blog/item/470fdac4491358cf38db494b.html

http://en.wikipedia.org/wiki/Dynamic_programming