HDU Problem 2005 另类做法

HDU题目2005具体详情

*ACM水题就要尝试多用其他方法解决.
尝试不一样的解题技巧,总有一天会用得上*

题目
给定一个日期,输出这个日期是该年的第几天。
Input
输入数据有多组,每组占一行,数据格式为YYYY/MM/DD组成,具体参见sample input ,另外,可以向你确保所有的输入数据是合法的。
Output
对于每组输入数据,输出一行,表示该日期是该年的第几天。
Sample Input
1985/1/20
2006/3/12
Sample Output
20
71
如下是代码的实现

#include<iostream>
#include<string>
#include<regex>
#include<cstdlib>
int main ()
{
  using namespace std;
  string a;
          const int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};//闰年的每个月天数
  regex  e("([0-9]*)\/([0-9]*)\/([0-9]*)");//匹配年、月、日
  int y , m , d;
  while(cin>> a )
  {
    int sum = 0;
    std::smatch sm;
    std::regex_match(a, sm ,e ,std::regex_constants::match_default);
    m = stoi( sm[2]);
    d = stoi( sm[3]);
    y = stoi( sm[1]);//这里要注意sm[0]是全部匹配,所以从1开始
    for(int i = 0 ; i < m-1 ; ++i)
      sum+=month[i];
    sum+=d;
    if(((y%4 == 0 && y%100 != 0)||(y%400 == 0)) && m>2)//是否闰年的判断方法
      sum++;
    cout << sum <<endl;
  }
  return 0;
}

主要使用了正则表达式,正则表达式在这类题看起来有点”杀鸡用牛刀”,但是如果遇见复杂的题是可以尝试一下这个方法的。

猜你喜欢

转载自blog.csdn.net/helloworld19970916/article/details/81326170