用C库函数time()计时+全排列(dfs)计时例子

time():

C 库函数 time_t time(time_t *seconds) 返回自纪元 Epoch(1970-01-01 00:00:00 UTC)起经过的时间,以秒为单位。如果 seconds 不为空,则返回值也存储在变量 seconds 中。

ctime():

C 库函数 char *ctime(const time_t *timer) 返回一个表示当地时间的字符串,当地时间是基于参数 timer

返回的字符串格式如下: Www Mmm dd hh:mm:ss yyyy 其中,Www 表示星期几,Mmm 是以字母表示的月份,dd 表示一月中的第几天,hh:mm:ss 表示时间,yyyy 表示年份。

声明:

time_t time(time_t *seconds)

参数:seconds -- 这是指向类型为 time_t 的对象的指针,用来存储 seconds 的值。

返回值:以 time_t 对象返回当前日历时间。

定时器代码:

#include <stdio.h>
#include <time.h>
time_t current, start;
int m = ????   //定时的时间,单位为s
int main()
{
    time(&start);
    cout << ctime(&start) << '\n';
    do
    {
        //操作数
        time(&current);
    }
    while((current - start) != m);
    cout << ctime(&current) << '\n';
    return 0;
}

 

下面给出一个全排列计时的栗子, 全排列实现方法为dfs,也可以理解为怎么在dfs中进行计时终结

全排列说明:

当 n = 4 时,共有 n!= 24 个全排列顺序,分别为:

可是我们知道,当 n = 10 时, n! = 3628800,但我们在跑数据的时候,只想跑5s或者10s的数据,这时候如何终止呢?

这里直接给出定时输出截图和代码,不懂的或者有更好方法的可在底下评论噢~~~~

由截图我们知道,大致运行时间是5s,虽然不是很精准,但应付一些定时需要还是有用的~~~~

 

运行代码:

//#include<bits/stdc++.h>
#include  <stdio.h>
#include <iostream>
#include<algorithm>
#include   <vector>
#include    <ctime>
#include   <time.h>
#include <unistd.h>

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAXN = 5*100005;
const double r = 0.57721566490153286060651209;//欧拉常数
const double pi = acos(-1);

static vector<int>x;
int ans = 1, flag = 1;
time_t current, start;
int m = 5, n = 10;        //定时5s,全排序n=10

void GG(int c, int n)
{
    if((current - start) >= m)
    {
        if(flag)                //输出一次时间
            cout << ctime(&current) << '\n';
        flag = 0;
        return ;
    }
    if(c <= n)
        for(int i=c; i<=n; ++i)
        {
            swap(x[c], x[i]);
            GG(c+1, n);
            swap(x[c], x[i]);
            time(&current);
        }
    else
    {
        cout << ans << ": \t";
        for(auto i: x)
            if(i != 0)
                cout << i << ' ';
        ans++;
        cout << '\n';
        return ;
    }
}

int main()
{
    for(int i=0; i<=n; ++i)
        x.push_back(i);
    time(&start);
    cout << ctime(&start) << '\n';
    do
    {
        GG(1, n);
        time(&current);
    }
    while((current - start) != m);
    //cout << ctime(&current) << '\n';
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值