天天看點

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);
	}
} 
           

繼續閱讀