CF1157A. Reachable Numbers

Let's denote a function f(x)f(x) in such a way: we add 11 to xx , then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,

  • f(599) = 6f(599)=6 : 599 + 1 = 600 ightarrow 60 ightarrow 6599+1=600606 ;
  • f(7) = 8f(7)=8 : 7 + 1 = 87+1=8 ;
  • f(9) = 1f(9)=1 : 9 + 1 = 10 ightarrow 19+1=101 ;
  • f(10099) = 101f(10099)=101 : 10099 + 1 = 10100 ightarrow 1010 ightarrow 10110099+1=101001010101 .

We say that some number yy is reachable from xx if we can apply function ff to xx some (possibly zero) times so that we get yy as a result. For example, 102102 is reachable from 1009810098 because f(f(f(10098))) = f(f(10099)) = f(101) = 102f(f(f(10098)))=f(f(10099))=f(101)=102 ; and any number is reachable from itself.

You are given a number nn ; your task is to count how many different numbers are reachable from nn .

输入输出格式

输入格式:

The first line contains one integer nn ( 1 le n le 10^91n109 ).

输出格式:

Print one integer: the number of different numbers that are reachable from nn .

输入输出样例

输入样例#1
1098
输出样例#1: 
20
输入样例#2: 
10
输出样例#2:
19


题意:

有一个函数f(x)f(x),效果是将x+1x+1后,去掉末尾所有的00,例如:

f(599)=6f(599)=6,因为599+1=600→60→6599+1=600606

f(7)=8f(7)=8,因为7+1=87+1=8

f(9)=1f(9)=1,因为9+1=10→19+1=101

f(10099)=101f(10099)=101,因为10099+1=10100→1010→10110099+1=101001010101

我们可以多次进行函数f(x)f(x)的运算,从而让一个数xx转换为另一个数,例如1009810098可以转换为102102,因为f(f(f(10098)))=f(f(10099))=f(101)=102f(f(f(10098)))=f(f(10099))=f(101)=102。

你需要做的是给你一个数nn,求出nn经过多次函数f(x)f(x)的计算,能转换为几个不同的数(包括自身)?

思路:直接模拟即可,将这个数++,如果后面有0,将零去掉,当某个数字重复时一定会绕回去,所以此时终止就行

可以用c++ set中的insert函数,因为insert函数不会插入重复值,所以可以利用insert作为结束条件

代码实现

#include<cstdio>
#include<set>
#include<iostream>
using namespace std;
set<int>s;
int main()
{
	int x;
	cin>>x;
	s.insert(x);
	while(x != 0){
		x++;
		while(x % 10 == 0){  // 去掉0 
			x /= 10;
		}
		int n = s.size();
		s.insert(x);
		if(s.size() == n){  //判断终止的条件,一开始n与s.size()总是差着一个值,如果有重复条件则s.size()不增加,n就等于s.size()
			cout<<n<<endl;
			return 0;
		}
	}
}

  

原文地址:https://www.cnblogs.com/clb123/p/10840999.html