随机数板子

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); 这行代码用于创建一个高质量的随机数生成器。让我详细解释每个部分:

完整代码示例

#include <iostream>
#include <random>
#include <chrono>
using namespace std;

int main() {
    // 创建随机数生成器
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    
    // 生成随机数
    cout << "随机整数: " << rng() << endl;
    
    // 生成指定范围的随机数
    uniform_int_distribution<int> dist(1, 100);
    cout << "1-100的随机数: " << dist(rng) << endl;
    
    return 0;
}

各部分解析

1. mt19937

  • Mersenne Twister 19937 伪随机数生成算法
  • 周期很长:2^19937 - 1
  • 生成高质量的随机数

2. chrono::steady_clock::now()

  • 获取当前时间点
  • steady_clock 是单调时钟,不会因系统时间调整而回退

3. .time_since_epoch()

  • 返回从时钟纪元(1970年1月1日)到现在的时间间隔

4. .count()

  • 将时间间隔转换为整数(通常是纳秒或微秒)
  • 作为随机数种子

在算法竞赛中的常见用法

基本随机数生成

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// 生成随机整数
int random_int = rng();

// 生成指定范围随机数 [a, b]
int random_in_range = rng() % (b - a + 1) + a;

使用分布类(推荐)

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// 整数均匀分布 [1, n]
uniform_int_distribution<int> dist1(1, n);
int x = dist1(rng);

// 实数均匀分布 [0.0, 1.0]
uniform_real_distribution<double> dist2(0.0, 1.0);
double y = dist2(rng);

随机打乱数组

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

vector<int> arr = {1, 2, 3, 4, 5};
shuffle(arr.begin(), arr.end(), rng);

替代方案

如果不想写这么长,也可以用简单版本:

// 简单版本(随机性稍差)
mt19937 rng(time(0));

// 或者使用随机设备(需要编译器支持)
random_device rd;
mt19937 rng(rd());

在题目代码中的使用

在你之前的代码中:

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// 打乱数组
shuffle(points.begin(), points.end(), rng);

// 或者生成随机索引
int random_index = rng() % points.size();

这样可以确保每次运行程序时都能获得不同的随机序列,对于随机化算法很重要。

posted @ 2025-11-05 22:11  miao-jc  阅读(9)  评论(0)    收藏  举报