小寄巧(c++环境包括c++98可用)
用于防止TLE,进行骗分。有一些相同作用的语句无法在c++98环境下运行,并且更为繁琐复杂难以记住。
程序开始前,也就是主函数第一行,记录开始时的时间 start :
clock_t start=clock();
在主要耗时间的地方,计算出当前程序耗时 TIME :
double TIME=static_cast<double>(clock()-start)/CLOCKS_PER_SEC;
追求简洁的话可以直接在程序开头加入一个定义:
#define TIME static_cast<double>(clock()-start)/CLOCKS_PER_SEC
需要获取时间的时候,直接使用 TIME 即可。但是记住,主函数开头仍然要定义 clock_t start=clock(); 。
在循环处(即耗时的地方)判断时间 TIME 是否达到临界,以0.99秒为佳:
if(TIME>=0.99)
{
cout<<ans<<endl;//反正就是输出答案
return 0;
}
实践到某道题目上。图为前后对比。
可以看到,是有一些效果的,并且加入时间计算语句后不会明显消耗更多时间。时间的计算大约有 2 至 4 ms的误差,影响不大。
附赠模板,免费拿走
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define R register
#define TIME static_cast<double>(clock()-start)/CLOCKS_PER_SEC
signed main()
{
clock_t start=clock();
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
return 0;
}