有n根厚度可以忽略不计的火柴,第i根火柴的长度为aj。 约翰想要从中选取四根火柴(显然每根火柴只能被选取一次),并用这四根火柴分别作为四条边围成 一个矩形。约翰想要你告诉他,在所有选取方案中,矩形面积的最大值是多少。
2条回答 默认 最新
- qfl_sdu 2021-05-22 14:54关注
代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h> #include <map> using namespace std; int main() { printf("请输入火柴的根数:"); int n; scanf("%d",&n); printf("请输入火柴的长度:"); int buf[100] = {0}; //存储火柴的长度 for(int i = 0; i < n; i++) scanf("%d",&buf[i]); //1.统计每种长度的火柴的根数,因为如果要组成矩形 //至少需要2根相同长度的火柴 map<int,int> mapLength; map<int,int>::iterator it = mapLength.begin(); for (int i = 0; i < n; i++) { it = mapLength.find(buf[i]); if (it == mapLength.end()) { mapLength.insert(pair<int,int>(buf[i],1)); }else { int len = it->second + 1; mapLength.erase(it); mapLength.insert(pair<int,int>(buf[i],len)); } } //2.将map中数量少于2的火柴删除 for (it = mapLength.begin(); it != mapLength.end(); ) { if (it->second < 2) { mapLength.erase(it); it = mapLength.begin(); }else it++; } for (it = mapLength.begin(); it != mapLength.end(); it++) printf("长度为%d的火柴数量=%d\n",it->first,it->second); //因为map能够根据key自动排序,且按照从小到大的顺序排列 //所以,map中最后一个元素是最长的火柴长度, //找最大矩形的话,就取最后两个元素的长度即可 int mj = 0; if (mapLength.size() < 2) { //如果map中没有2组相同长度的火柴,则说明无法组成矩形 //do nothing printf("无法组成矩形\n"); }else { it = mapLength.end(); it--; int leng = it->first; it--; int leng2 = it->first; mj = leng * leng2; printf("最大面积=%d * %d = %d\n",leng,leng2,mj); } getchar(); getchar(); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报