天天看点

sicily 1240. Faulty Odometer 1240. Faulty Odometer Constraints Description Input Output Sample Input Sample Output

1240. Faulty Odometer

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

You are given a car odometer which displays the miles traveled as an integer. The odometer has a defect, however: it proceeds from the digit 3 to the digit 5, always skipping over the digit 4. This defect shows up in all positions (the one's, the ten's, the hundred's, etc.). For example, if the odometer displays 15339 and the car travels one mile, odometer reading changes to 15350 (instead of 15340).

Input

Each line of input contains a positive integer in the range 1..999999999 which represents an odometer reading. (Leading zeros will not appear in the input.) The end of input is indicated by a line containing a single 0. You may assume that no odometer reading will contain the digit 4.

Output

Each line of input will produce exactly one line of output, which will contain: the odometer reading from the input, a colon, one blank space, and the actual number of miles traveled by the car.

Sample Input

13
15
2003
2005
239
250
1399
1500
999999
0

      

Sample Output

13: 12
15: 13
2003: 1461
2005: 1462
239: 197
250: 198
1399: 1052
1500: 1053
999999: 531440      

这道题用9进制可以水过,从左往右推就好,记得如果当前位数大于等于4就要减去1。

#include <iostream>
#include <string>
#include <cstdio> 
using namespace std;


int main()
{
	string num;
	while(cin>>num&&num!="0")
	{
		int ans=0;
		for(int i=0;i<num.length();i++)
		{
			ans*=9;
			if(num[i]>'4')
			ans--;
			ans+=num[i]-'0';
		}
		printf("%s: %d\n",num.c_str(),ans);
	}
}
           

不想水就用DP递推咯,预处理dp[i][j]表示位数为j的时候,并且最左边也就是最高位是i的这些数中包含4的有多少种,比如dp[1][3]就表示1xx中有多少个包含4的数。如果i不为4,dp[i][j]=sum{dp[k][j-1]}(0<=k<=9),如果i为4那么dp[i][j]=10^(j-1)。 预处理完毕后也要分情况。比如数是356,先算百位,0xx,1xx,2xx,再算十位,0x-4x,再算个位。如果遇到当前位是4,直接把后面的加上就行了。

#include <bits/stdc++.h>
using namespace std;
int dp[10][12];

void init(){
	for(int i=0;i<=9;i++)
	dp[i][1]=(i==4);
	
	for(int i=2;i<=10;i++){
		for(int j=0;j<=9;j++){
			if(j!=4){
				dp[j][i]=0;
				for(int k=0;k<=9;k++)
				dp[j][i]+=dp[k][i-1];
			}
			else if(j==4){
				dp[j][i]=pow(10,i-1);
			}
		}
	}	
}
int len(int number){
	int countt=0;
	while(number){
		number/=10;
		countt++;
	}
	return countt;
}
int main(){
	int number;
	init();	//先预处理 
	while(scanf("%d",&number)&&number){
		int length=len(number);
		int tmp=number+1;
		int ans=0;
		while(tmp){
			int cur=tmp/pow(10,length-1);
			tmp=tmp-cur*pow(10,length-1);
			for(int i=0;i<cur;i++)
			ans+=dp[i][length];
			if(cur==4){
				ans+=tmp;
				break;
			}
			length--;
		}
		printf("%d: %d\n",number,number-ans);
	}
} 
           

继续阅读