小蓝现在有一个长度为 100 的数组,数组中的每个元素的值都在 0 到 9 的
范围之内。数组中的元素从左至右如下所示:
5 6 8 6 9 1 6 1 2 4 9 1 9 8 2 3 6 4 7 7 5 9 5 0 3 8 7 5 8 1 5 8 6 1 8 3 0 3 7 9 2
7 0 5 8 8 5 7 0 9 9 1 9 4 4 6 8 6 3 3 8 5 1 6 3 4 6 7 0 7 8 2 7 6 8 9 5 6 5 6 1 4 0 1
0 0 9 4 8 0 9 1 2 8 5 0 2 5 3 3
现在他想要从这个数组中寻找一些满足以下条件的子序列:
可以通过枚举所有可能的子序列来解决这个问题。先通过循环来枚举所有可能的子序列,然后检查每个子序列是否满足条件。如果满足条件,则将其添加到一个集合中(此算法使用set,不会出现重复项),以便统计不同的日期数。最后,返回集合中不同日期的数量。
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
int a[100] = {5, 6, 8, 6, 9 // ...
};
set<string> dates;
for (int i = 0; i < sizeof(a) / sizeof(int) -7; i++) {
string date = to_string(a[i]) + to_string(a[i+1]) + to_string(a[i+2]) + to_string(a[i+3]) + to_string(a[i+4]) + to_string(a[i+5]) + to_string(a[i+6]) + to_string(a[i+7]);
if (date >= "20230101" && date <= "20231231") {
string year = date.substr(0,4);
string month = date.substr(4,2);
string day = date.substr(6);
dates.insert(year + "-" + month + "-" + day);
}
}
cout << "不同日期数:" << dates.size() << endl;
return 0;
}
编程基础第六版 课后题
代码如下
#include <stdio.h>
#include <math.h>
int main()
{
int i,j,t;
int a[15];
int x,l,h,mid,n;
n=15;
l=0;
h=n-1;
printf("请输入15个不同数字,按一次输入一个,依次输入15次的方法输入数字:\n");
for(i=0;i<15;i++)
scanf("%d",&a[i]);
for(j=0;j<14;j++)
{
for(i=0;i<14-j;i++) //这里我第一次写也忽略了j要不断的去替换i,所以对于i来说它的循环条件应该是14-j,有好多人可能和我一样写成i<15啦
if( a[i]<a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
printf("按从大到小的排序结果:");
for( i=0;i<15;i++)
printf("%d\t",a[i]);
printf("\n");
for (l=0, h=14, printf("请输入一个数:"), scanf("%d", &x); l<=h;)//while也可以但是我很奇怪用while会提前退出循环哈哈哈
{
mid=(l+h)%2;
if (x>a[mid])h=mid-1;
else if (x<a[mid])l=mid+1;
else
{
printf("%d是第%d位数",x,mid+1);
break;
}
}
if(x!=a[mid])
printf("查无此数!");
return 0;
}