随机产生N个中和为1的(0-1)之间的数

本文介绍了一种生成特定数量随机数的方法,这些随机数加总等于1,适用于概率分配等场景。通过循环和随机数生成函数实现,确保了生成的随机数符合要求。
function [MYANS] = myNRandPlusEqualOne(N)
%param N 表示要生成多少个随机数
%return MYANS--N*1
%function 函数是为了生成N个加起来和为1的向量
%CopyRight NUST CS726 Jun.H(111060881)


tempANS = zeros(N, 1);
res = 1;
for R=1:N-1
    t = rand();
    if t<0 || t>1
        error('rand function create a value is not in [0, 1]');
    end
    tempANS(R, 1) = res*t;
    res = res*(1-t);
end
tempANS(N, 1) = res;
MYANS = tempANS;
给定 n 个整组成的序列 { a 1 ​ ,a 2 ​ ,⋯,a n ​ },“连续子序列”被定义为 { a i ​ ,a i+1 ​ ,⋯,a j ​ },其中 1≤i≤j≤n。“连续子序列最大”则被定义为所有连续子序列元素的中最大者。例如给定序列 { -2, 11, -4, 13, -5, -2 },其连续子序列 { 11, -4, 13 } 有最大的 20。请编写程序,计算给定整序列的连续子序列最大。 本题旨在测试各种不同的算法在各种据情况下的表现。各组测试据特点如下: 0~6:测试基本正确性; 据 7:10 3 个随机据 8:10 4 个随机据 9:10 5 个随机。 输入格式: 输入第一行给出正整 n (10 5 );第二行给出 n 个整,绝对值均不超过 100,其间以空格分隔。 输出格式: 在第一行中输出连续子序列最大,第二行输出该子序列首尾的组下标(从 0 开始),以 1 个空格分隔。若解不唯一,则输出最小的组下标(如样例所示)。 注意:如果序列中所有整皆为零或负,则取空子列的结果是最大的,为 0;此时空子序列组首尾的下标均为 -1。 输入样例: 10 -10 2 2 3 4 -5 -23 4 7 -21 输出样例: 11 1 4#include <iostream> #include <vector> #include <climits> using namespace std; pair<int, pair<int, int>> maxSubarraySum(const vector<int>& nums) { int n = nums.size(); if (n == 0) return {0, {-1, -1}}; int max_sum = INT_MIN; int current_sum = 0; int start_index = 0, end_index = 0, temp_start = 0; for (int i = 0; i < n; ++i) { current_sum += nums[i]; if (current_sum > max_sum) { max_sum = current_sum; start_index = temp_start; end_index = i; } if (current_sum < 0) { current_sum = 0; temp_start = i + 1; } } // 特殊情况:所有元素都为非正 bool all_non_positive = true; for (int num : nums) { if (num > 0) { all_non_positive = false; break; } } if (all_non_positive) { return {0, {-1, -1}}; } return {max_sum, {start_index, end_index}}; } int main() { int n; cin >> n; vector<int> arr(n); for (int i = 0; i < n; ++i) { cin >> arr[i]; } auto result = maxSubarraySum(arr); cout << result.first << endl; cout << result.second.first << " " << result.second.second << endl; return 0; } 详细解释
最新发布
07-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jun-H

你的鼓励是我创作的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值