random_shuffle();随机分配函数和数的运用

random_shuffle()函数

这是c++库内的随机分配函数,将起始地址到末端地址的前一个地址之间的数随机存。
具体使用这里给一个网址函数教程

一个数的运用

如果是数组,从0开始的数组,想弄成循环数组计算,可以使用(i+j)%n(注:n是这个数组的长度j是要加的数,i是现在的位置)

例题

输入:
一个数t,循环t次,输入n,然后输入2n个数。
输出:
将2n个数输出,其中任意i-1和i+1之和不等于i的两倍,且是个循环的数组2n+1是第一个也满足此条件。
题目链接
代码如下:
超级暴力的解题方法

#include<iostream>
#include<stack>
#include<string>
#include<algorithm>

#define bug(a) (cout<<"*"<<a<<endl)
#define bugg(a,b) (cout<<"*"<<a<<' '<<b<<endl)
#define buggg(a,b,c) (cout<<"*"<<a<<' '<<b<<' '<<c<<endl)
#define endl '\n'
#define MAX 0x3f3f3f
using namespace std;
typedef long long ll;

int arr[100];
int main()
                                                                                                                                                            {
	ios::sync_with_stdio(false);
	cin.tie();
	cout.tie();
	
	int n,i,j,t;
	cin >> t; 
	while(t--){
		cin >> n;
		n *= 2;
		for (i = 0; i < n; i++)
			cin >> arr[i];
		while (1) {
			bool flag = true;
			random_shuffle(arr, arr + n);
			for (i = 0; i < n; i++) {
				if (arr[i] + arr[(i + 2) % n] == 2 * arr[(i + 1) % n])
					flag = false;
			}
			if (flag)break;
		}
		for (i = 0; i < n; i++)
			cout << arr[i] << ' ';
		cout << endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果编译时提示 `random_shuffle()` 函数未定义,可能是因为您的编译器版本太老,不支持 C++11 标准的随机库。可以将以下代码: ```c++ srand((unsigned)time(NULL)); // 初始化随机种子 ``` 替换为: ```c++ std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count()); ``` 并在程序开头加入头文件: ```c++ #include <random> #include <chrono> ``` 然后将 `random_shuffle()` 函数替换为: ```c++ std::shuffle(num.begin(), num.end(), rng); ``` 这样就可以使用 C++11 提供的随机库了。下面是修改后的程序: ```c++ #include <iostream> #include <random> #include <chrono> #include <vector> #include <algorithm> using namespace std; int main() { std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count()); // 初始化随机生成器 vector<int> num(35), red(12), blue(5); // 定义号码组 for (int i = 0; i < 35; i++) { num[i] = i + 1; // 初始化号码组 } for (int k = 0; k < 5; k++) { // 机选 5 注 // 随机选取红球号码 std::shuffle(num.begin(), num.end(), rng); // 打乱号码顺序 for (int i = 0; i < 2; i++) { red[i] = num[i]; // 选取号码 } sort(red.begin(), red.end()); // 对红球号码排序 // 随机选取蓝球号码 std::shuffle(num.begin(), num.end(), rng); // 打乱号码顺序 for (int i = 0; i < 5; i++) { blue[i] = num[i]; // 选取号码 } sort(blue.begin(), blue.end()); // 对蓝球号码排序 // 输出结果 cout << "第 " << k + 1 << " 注:" << endl; cout << "红球号码:"; for (int i = 0; i < 2; i++) { cout << red[i] << " "; } cout << endl << "蓝球号码:"; for (int i = 0; i < 5; i++) { cout << blue[i] << " "; } cout << endl << endl; } return 0; } ``` 这个程序使用了 C++11 中的随机库,可以保证号码的随机性和唯一性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我已经怒不可遏了!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值