1.回文日期


思路
需要编写几个函数
1)从int转换为指定位数的string的函数
2)从string转换为int的函数
3)判断闰年的函数
4)判断日期是否合法的函数
5)判断字符串是否是回文的函数
6)判断字符串是否是ABABBABA型回文的函数
#include<bits/stdc++.h>
using namespace std;
int s2i(string s) // string到int
{
int res = 0;
for(const auto &i : s)res = res * 10 + i - '0';
return res;
}
string i2s(int x, int w) // 数字转换为指定位置的字符串
{
// w 指定位数
string res;
while (x)res += (x % 10) + '0', x /= 10;
while(res.length() < w)res += '0'; // 如果长度小于指定位数后面加 0
reverse(res.begin(), res.end()); // 反转
return res;
}
bool isleapYear(int year) // 判断闰年
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
bool isok(int year, int month, int day) //判断一个日期是否合法
{
int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(isleapYear(year))days[2] = 29;
return day <= days[month];
}
bool ispa1(string s)// 是否是回文
{
for(int i = 0;i < s.length() / 2; ++ i)
{
if(s[i] != s[s.length() - 1 - i])return false;
}
return true;
}
bool ispa2(string s) // 判断是否是ABABBABA型回文
{
if( ! ispa1(s))return false;
return s[0] == s[2] && s[1] == s[3];
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
string s; cin >> s; // 输入8位数日期
int year = s2i(s.substr(0, 4)), month = s2i(s.substr(4, 2)), day = s2i(s.substr(6, 2));
bool ans1 = false, ans2 = false; // 留两个变量判断是否找到答案
for(int i = year;i <= 9999; ++ i) // 枚举
{
for(int j = 1;j <= 12; ++ j)
{
if(i == year && j < month)continue; // 月份只能在输入的月份之后
for(int k = 1;k <= 31; ++ k)
{
if(i == year && j == month && k <= day)continue; // 日期只能在输入的之后
if( ! isok(i, j, k))continue; // 如果日期不合法的话跳过
string date = i2s(i, 4) + i2s(j, 2) + i2s(k, 2);
if( ! ans1 && ispa1(date))
{
cout << date << "\n";
ans1 = true;
}
if( ! ans2 && ispa2(date))
{
cout << date << "\n";
ans2 = true;
}
}
}
}
return 0;
}
2.最大数组和



#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main ()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t ; cin >> t;
while(t -- )
{
int n, k; cin >> n >> k;
vector<int> a(n);
for (int i = 0;i < n; ++ i)
{
int x ; cin >> x;
a[i] = x;
}
sort(a.begin(), a.end());
vector<ll> pre(n + 1);
for (int i = 1;i <= n; ++ i)pre[i] = pre[i - 1] + a[i - 1];
ll ans = 0;
for(int i = 0;i <= k; ++ i)
{
ans = max(ans, pre[n - (k - i)] - pre[2 * i]);
}
cout << ans << "\n";
}
return 0;
}
文章介绍了如何通过编程实现从字符串转换为整数,判断闰年和日期合法性,以及检查回文字符串(包括ABABBABA型)。主要内容围绕日期处理和数组操作算法的实现。
878

被折叠的 条评论
为什么被折叠?



