Life of xhu

About

HOJ_1071解答(未完成)

Jan 20, 2014

  |   #C++   |   #HOJ

今天突然想上HOJ做道简单题,鼠标随便一点就进了这道题

输入输出都是一堆纯数字,直觉告诉我应该不会是一道特别难的题,于是开始动手做,果然不是很难,我想真正的ACM大牛是绝对不屑于做这种题的。。。

写好代码,submit之,Time Limit Exceed。。。

看了一会儿代码,没发现有很复杂的地方,突然想到,会不会是因为用了好几个函数的缘故?

google了一下,发现了一个解释:

在程序运行的时候,在程序进程中调用函数时,程序会有一个压栈操作,即将当前的数据存储起来,转到目标函数中执行,所以大量的调用函数,必然会造成额外时间开销。

仔细想想,我发现我现在编程养成了两个习惯:

  1. C++时喜欢把各种操作放在函数中,main函数只有寥寥几行。

  2. Ruby时喜欢把所有的操作放在里面,开始编程二话不说先建一个class。。。

平时我还觉得我这两个习惯挺好的,因为这样做之后,代码的确更简洁好看了。但是这时好像第一个习惯影响到做题了,算了,改吧。

一会儿把代码改好了,所有的函数内容都放进了main里面,运行,结果正确,submit之,继续Time Limit Exceed。。。

今天对这道题的折腾就到此为止吧,如果以后我有兴趣了,再找大牛给我看看代码。

唉,果然不是搞ACM的命。。。

最后啰嗦一句,我总觉得1071给出的最后一组例子有错,因为相同的起止时间,以60分钟为单位输出11,以1小时为单位却输出10,难道60 minutes != 1 hour

代码如下:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main(){
    int days, hours, minutes, seconds;
    int tmp1, tmp2;
    int start[6], end[6];
    int unit1;
    string unit2;

    while(true){
        cin >> start[0] >> start[1] >> start[2] >> start[3] >> start[4] >> start[5];
        cin >> end[0] >> end[1] >> end[2] >> end[3] >> end[4] >> end[5];
        cin >> unit1 >> unit2;

        days = end[2];
        end[1] = (end[0] - start[0]) * 12 + end[1];
        for(int i = start[1]; i < end[1]; i++){
            if(i % 12 == 0)
                days += 31;
            else{
                tmp1 = start[0] + i / 12;
                tmp2 = i % 12;
                if(tmp2 == 2){
                    if(tmp1 % 4 != 0)
                        days += 28;
                    else{
                        if(tmp1 % 100 != 0)
                            days += 29;
                        else{
                            if(tmp1 % 400 == 0)
                                days += 29;
                            else
                                days += 28;
                        }
                    }
                }else if(tmp2 == 4 || tmp2 == 6 || tmp2 == 9 || tmp2 == 11)
                    days += 30;
                else
                    days += 31;
            }
        }
        days = days - start[2];
        hours = days * 24 + end[3] - start[3];
        minutes = hours * 60 + end[4] - start[4];
        seconds = minutes * 60 + end[5] - start[5];
        //cout << days << ' ' << hours << ' ' << minutes << ' ' << seconds << endl;
        if(unit2 == "day")
            cout << days / unit1 << endl;
        else if(unit2 == "hour")
            cout << hours / unit1 << endl;
        else if(unit2 == "minute")
            cout << minutes / unit1 << endl;
        else if(unit2 == "second")
            cout << seconds / unit1 << endl;
    }
}