Run ID:148837
提交时间:2026-03-01 19:04:15
#include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; // 分割字符串函数,用于解析日期 vector<string> split(const string &s, char delimiter) { vector<string> tokens; string token; istringstream tokenStream(s); while (getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } // 判断是否为闰年 bool isLeapYear(int year) { // 闰年规则: // 1. 能被400整除 // 2. 能被4整除但不能被100整除 if (year % 400 == 0) { return true; } if (year % 100 == 0) { return false; } if (year % 4 == 0) { return true; } return false; } // 每个月的天数(非闰年) int monthDays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 计算从0年到指定日期的总天数 long long calculateTotalDays(int year, int month, int day) { long long total = 0; // 加上整年的天数 for (int i = 0; i < year; ++i) { total += isLeapYear(i) ? 366 : 365; } // 加上整月的天数 for (int i = 1; i < month; ++i) { if (i == 2 && isLeapYear(year)) { total += 29; } else { total += monthDays[i]; } } // 加上天数 total += day; return total; } // 检查日期是否合法 bool isValidDate(int year, int month, int day) { if (month < 1 || month > 12) return false; if (day < 1) return false; // 检查2月 if (month == 2) { if (isLeapYear(year)) { return day <= 29; } else { return day <= 28; } } // 检查其他月份 return day <= monthDays[month]; } // 计算从出生到18岁生日的天数 long long calculate18BirthdayDays(const string& birthDate) { // 解析日期 vector<string> parts = split(birthDate, '-'); if (parts.size() != 3) return -1; int birthYear, birthMonth, birthDay; try { birthYear = stoi(parts[0]); birthMonth = stoi(parts[1]); birthDay = stoi(parts[2]); } catch (...) { return -1; // 转换失败 } // 检查出生日期是否合法 if (!isValidDate(birthYear, birthMonth, birthDay)) { return -1; } // 计算18岁生日的日期 int birthday18Year = birthYear + 18; // 检查18岁生日是否存在 if (!isValidDate(birthday18Year, birthMonth, birthDay)) { return -1; } // 计算总天数差 long long daysBirth = calculateTotalDays(birthYear, birthMonth, birthDay); long long days18 = calculateTotalDays(birthday18Year, birthMonth, birthDay); return days18 - daysBirth; } int main() { int T; // 读取测试用例数量 cin >> T; cin.ignore(); // 忽略换行符 // 处理每个测试用例 for (int i = 0; i < T; ++i) { string birthDate; getline(cin, birthDate); long long result = calculate18BirthdayDays(birthDate); cout << result << endl; } return 0; }