这套卷子两个小时,五道题,我一个下午才做出来两道题;真的是力不从心啊,思路不算难,但是自己老是写错数组的一下处理。
1.度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?
输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)
输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1
输入例子1:
10 10 10 10 10 20 20 30 30 40 40
输出例子1:
30
#include "stdio.h"
int main(){
int price[50];
int third, index, total;
int temp;
scanf("%d",&total);
for (index = 0; index < total;index++){
scanf("%d", &price[index]);
}
if (index < 3){
printf("%d\n", -1);
return 0;
}
for (index = 0; index < total; index++){
for (int i = 1; i < total; i++){
if (price[i] < price[i - 1]){
temp = price[i];
price[i] = price[i - 1];
price[i - 1] = temp;
}
}
}
index = 0;
third = 0;
for (index = 0; index < total; index++){
if (price[index]<price[index + 1]){
third++;
if (third == 2){
printf("%d\n", price[index+1]);
return 0;
}
}
}
printf("%d\n", -1);
return 0;
}
这道题我的解法很菜,我是先排序,然后从最小的一个元素开始找,找到一个比他大的,third加一,找到两个比他大的,之后就是第三便宜的了。
最优解应该是用set容器做,很简单的;
2.一个数轴上共有N个点,第一个点的坐标是度度熊现在位置,第N-1个点是度度熊的家。现在他需要依次的从0号坐标走到N-1号坐标。
但是除了0号坐标和N-1号坐标,他可以在其余的N-2个坐标中选出一个点,并直接将这个点忽略掉,问度度熊回家至少走多少距离?输入描述:
输入一个正整数N, N <= 50。 接下来N个整数表示坐标,正数表示X轴的正方向,负数表示X轴的负方向。绝对值小于等于100
输出描述:
输出一个整数表示度度熊最少需要走的距离。
输入例子1:
4 1 4 -1 3
输出例子1:
4
#include <stdio.h>
#include <math.h>
int aabs(int a,int b){
int x =a-b;
if(x<0){
x = 0 - x;
}
return x;
}
int main(){
int point[50];
int destens[50],dest[50];
int index, total, farthest,des,flag;
scanf("%d",&total);
if (total<3){
return 0;
}
for (index = 0; index < total; index++){
scanf("%d",&point[index]);
}
farthest = 0;
for (index = 0; index < total - 1; index++){
dest[index] = aabs(point[index] , point[index+1]);
}
for (index = 1; index < total - 1; index++){
destens[index] = dest[index] + dest[index - 1];
if (farthest < destens[index]){
flag = index;
farthest = destens[index];
}
}
dest[flag - 1] = aabs(point[flag-1] , point[flag + 1]);
des = 0;
for (index = 0; index < total - 1; index++){
if (index == flag)
continue;
des += dest[index];
}
printf("%d",des);
return 0;
}
这道题网上的最优解我还没看,我自己的思路就是,先求每个点之间的距离,每个点到前一个点和后一个点距离之和最大的那个点就要删除,然后重新计算去掉这个点之后,这个点的后一个点到这个点的前一个点的距离,然后,去掉这个点求和;