Old_Bill(上海交大复试上机题)
编程废物在此,总共用了快一个小时才做出来,也太废了!!!
这道题大概题意就是:
【题目大意】N只火鸡的价格为XYZ,火鸡的总数N在1到99之间。价格由五位数组成,两边的数字由于褪色而看不清,所以只能看到中间的三位数。假设第一个数字非零,每只火鸡的价格是整数,并且所有火鸡的价格相同。给定N,X,Y和z,编写一个程序来猜测两边褪色的数字和火鸡的原始价格。如果有多个价格符合题意,那么输出最昂贵的那个。
原题目描述
Among grandfather’s papers a bill was found. 72 turkeys $
.The first and the last digits of the number that obviously represented the total price of those turkeys are replaced here by blanks (denoted_), for they are faded and are illegible. What are the two faded digits and what was the price of one turkey? We want to write a program that solves a general version of the above problem. N turkeys $
The total number of turkeys, N, is between 1 and 99, including both. The total price originally consisted of five digits, but we can see only the three digits in the middle. We assume that the first digit is nonzero, that the price of one turkeys is an integer number of dollars, and that all the turkeys cost the same price. Given N, X, Y, and Z, write a program that guesses the two faded digits and the original price. In case that there is more than one candidate for the original price, the output should be the most expensive one. That is, the program is to report the two faded digits and the maximum price per turkey for the turkeys.
输入描述:
The first line of the input file contains an integer N (0<N<100), which represents the number of turkeys. In the following line, there are the three decimal digits X, Y, and Z., separated by a space, of the original price $XYZ.
输出描述:
For each case, output the two faded digits and the maximum price per turkey for the turkeys.
代码(纯暴力枚举)
#include<iostream>
using namespace std;
void isPrice(int n, int num){
int max = 0;
int A, B;//分别代表第一位数和最后一位数 __XYZ__ a X Y Z b
for(int a = 1; a <= 9; a++){
for(int b = 0; b <= 9; b++){
if((a * 10000 + num + b) % n == 0){
int price = a * 10000 + num + b;
if(price >= max){ //判断是否为最大值
max = price;
A = a;
B = b;
}
}
}
}
if(max == 0){
cout << "0" << endl;
}else{
cout << A << " " << B << " " << (max / n) << endl;
}
}
int main(){
int n, x, y, z;
while(cin >> n){
cin >> x >> y >> z;
int num = x * 1000 + y * 100 + z * 10;
isPrice(n, num);
}
return 0;
}看到别人的题解思路中:
循环从9递减可以避免去判断是否为最昂贵的价格,但凡出现的第一个则为价格最贵的,跳出循环即可。
尝试一下
代码(循环优化)
void isPrice(int n, int num){
int max = 0, flag = 0; ////0代表未找到最佳答案
int a, b;//分别代表第一位数和最后一位数 __XYZ__ a X Y Z b
for(a = 9; a >= 1; a--){
for(b = 9; b >= 0; b--){
if((a * 10000 + num + b) % n == 0){
max = a * 10000 + num + b;
cout << a << " " << b << " " << (max / n) << endl;
flag = 1; //1代表已找到最佳答案,可以跳出循环
break;
}
}
if(flag){
break;
}
}
if(max == 0){
cout << "0" << endl;
}
}

查看18道真题和解析