gpt4 book ai didi

c++ - 有史以来数量最多的恐龙

转载 作者:行者123 更新时间:2023-11-30 21:47:13 26 4
gpt4 key购买 nike

Possible Duplicate:
algorthim to solve find max no at a time

给定一个由 2n 个整数组成的数组,其中该整数数组中的每一对分别代表恐龙的出生年份和死亡年份。我们要考虑的有效年份范围是[-100000 到 2005]。例如,如果输入是:

-80000 -79950 20 70 22 60 58 65 1950 2004

这意味着第一只恐龙的出生年份和死亡年份分别为 –80000 和 –79950。同样,第二只恐龙的生命周期为 20 岁到 70 岁,依此类推。

我们想知道曾经存活过的恐龙数量最多。给定上面的 2n 个整数数组,编写一个方法来计算这个值。

这是我迄今为止尝试过的:

#include<stdio.h>
#include<stdlib.h>
#include <stddef.h>

static void insertion_sort(int *a, const size_t n)
{
size_t i, j;
int value;
for (i = 1; i < n; i++) {
value = a[i];
for (j = i; j > 0 && value < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = value;
}
}

int main(){
int arr[10]={-80000,-79950,20,70,22,60,58,65,1950,2004};
int strt[5],end[5];
int bal[5];
int i,j,k,l,m,length;
l=0;
m=0;

for (i=0; i<10; i++){
//printf("i = %2d arr[i] = %2d\n", i, arr[i]);
if(i%2==0) {
strt[l]=arr[i];
l++;
} else {
end[m]=arr[i];
m++;
}
}

insertion_sort(strt, sizeof strt / sizeof strt[0]);
insertion_sort(end, sizeof end / sizeof end[0]);
k=sizeof(end)/sizeof(int);

for(j=0;j<5;j++) {
bal[i]=strt[i]-end[k-1];
k--;
}
length=sizeof bal / sizeof bal[0];
insertion_sort(bal, sizeof bal / sizeof bal[0]);
printf("answer is = %2d",bal[length-1]);
}

最佳答案

我会做这样的事情:

  1. 创建一个 map 来保存数据
  2. 成对阅读
  3. 对于 i =pair.first 到pair.second++map[i]
  4. 如果有更多对,则从 2 重复
  5. 查找 map 中计数最大的元素。该元素的关键是年份。

理论上,您可以使用 vector 代替 map ,但它的人口可能足够稀疏,因此 map 更有意义。

关于c++ - 有史以来数量最多的恐龙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com