1、日期统计

题目 日期统计

image-22ba0b4b
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

思路分析

子序列 不连续的也是子序列 比如 abcdef 其中bdf也是他的一个子序列

如果是连续的话 这题就比较好写

滑动窗口截断八个即可 再拿得到的字符串去检查是否为合法日期以及是否在2023年内

#include<bits/stdc++.h>

using namespace std;

const int N=110;

int a[N];

int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};

bool isleap(int y){

	return y%100 && y%4==0 || y%400==0;

}

int getdays(int y,int m){

	return days[m]+(m==2 && isleap(y));

}

bool checkdate(int y,int m,int d){

	if(m<1 || m>12)	return false;

	if(d<1 || d>getdays(y,m)) return false;

	return true;

}

int main()

{

	int n=100;

	for(int i=0;i<n;i++)

		cin>>a[i];

	int cnt=0;

	for(int i=7;i<n;i++){

		int j=i-7;

		string s;

		for(int k=j;k<=i;k++)

			s+=to_string(a[k]);

		int cury=stoi(s.substr(0,4));

		int curm=stoi(s.substr(4,2));

		int curd=stoi(s.substr(6,2));

		cout<<"s: "<<s<<endl<<" y: "<<cury<<" m: "<<curm<<" d: "<<curd<<endl;

		if(checkdate(cury,curm,curd)){

			if(cury==2023){

				cout<<cury<<" "<<curm<<" "<<curd<<endl;

				cnt++;

			}

		}

	}

	cout<<cnt;

	return 0;

 }

可问题是这题是子序列 间隔的也算

以这种思路的话就不可行了 把所有的子序列找出来显然不可能

只能反向思考一下

先枚举2023年份的所有日期 再检查会不会在原本字符串中出现

检查子串问题 双指针第三个模版

长的序列里的指针一直走 只有匹配了 短序列的指针才走

若到了最后 短序列指针位于短序列末尾 说明匹配成功

第一题写了40多分钟……醉了

代码实现

#include<bits/stdc++.h>

using namespace std;

const int N=110;

char a[N];

int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};

bool isleap(int y){

	return y%100 && y%4==0 || y%400==0;

}

int getdays(int y,int m){

	return days[m]+(m==2 && isleap(y));

}

void nextday(int &y,int &m,int &d){

	d++;

	if(d>getdays(y,m)){

		d=1;

		m++;

		if(m>12){

			m=1;

			y++;

		}

	}

}

//bool checkdate(int y,int m,int d){

//	if(m<1 || m>12)	return false;

//	if(d<1 || d>getdays(y,m)) return false;

//	return true;

//}

//在a串中 找是否出现子序列s

bool check(char *s){

	int big=100,small=8;

	int j=0;

	for(int i=0;i<big;i++){

		if(j<small && a[i]==s[j]){

			j++;

		}

	}

	if(j==small)

		return true;

	else

		return false;

}

int main()

{

	int n=100;

	for(int i=0;i<n;i++)

		cin>>a[i];

	int cnt=0;

	int cury=2023,curm=1,curd=1;

	while(cury<2024){

	//	cout<<cury<<" "<<curm<<" "<<curd<<endl;

		char s[10];

		sprintf(s,"%04d%02d%02d",cury,curm,curd);

//		cout<<s<<endl;

		if(check(s))

			cnt++;

		nextday(cury,curm,curd);

	}

	cout<<cnt;

	return 0;

 }

同类题型

视频讲解


⬅️ 10、砍树 🏠 00-刷题理模型 ➡️ 2、01串的熵