C++ Implementation of PTA Ladder Competition L1-033 Year of Birth

 

The above is a wonderful post on Sina Weibo: "I was born in 1988, and I didn't encounter a year with four different numbers until I was 25." That is to say, it was not until 2013 that "four numbers are different" was reached. requirements. For this question, please fill in the sentence "I was born in  y2009, and  I didn't xmeet  na year with different numbers until 2000" according to the requirements.

Input format:

yEnter the number of different digits in the year of birth and target year given in one line n, where it yis between [1, 3000] and ncan be 2, or 3, or 4. Note that the year with less than 4 digits should be filled with zeros in front. For example, the year 1 AD is considered to be 0001, and there are 2 different numbers 0 and 1.

Output format:

According to the input, the output xand the year that can meet the requirements. Numbers are separated by a space, and there must be no extra spaces at the beginning and end of the line. The year should be output in 4 digits. Note: The so-called " nthe numbers are not the same" means that the different numbers are exactly none. For example, "2013" is considered to meet the condition of "all 4 digits are different", but it is not considered to meet the condition of 2 or 3 digits being different.

Input sample 1:

1988 4

Output sample 1:

25 2013

Input sample 2:

1 2

Output sample 2:

0 0001

Problem-solving ideas: 

① Add 0 in front of the year with less than four digits

② Convert the year to a string

③ Use the deduplication function of the set container to store each digit in the string into the set container

④ See if the size of the set container (the number of different numbers) meets the requirements

⑤ Output as required

Code example:

#include <bits/stdc++.h>

using namespace std;

//对年份补0的函数
string deal(string str) {
	int cnt = 4 - str.length();
	for (int i = 0; i < cnt; i++) {
		str = "0" + str;
	}
	return str;
}

int main() {
	int year, propose;
	cin >> year >> propose; //起始年份  不同数字的个数

	int interval = 0; //间隔(年龄)

	while (true) {
		string str_year = to_string(year); //将年份转为字符串
		if (str_year.length() != 4) {
			str_year = deal(str_year); //对年份补0
		}

		set<int> type_num; //去重容器set
		for (auto num : str_year) {
			type_num.insert(num - '0');
		}
        
        //看set容器的大小(不同数字的多少)是否符合要求
		if (type_num.size() != propose) { 
			year++;
			interval++;
		}
		else {
			cout << interval << " ";
			printf("%04d\n", year);
			break;
		}
	}

	return 0;
}

Submit results: 

Guess you like

Origin blog.csdn.net/m0_53209892/article/details/128008809