#include <iostream>
#include <cmath>
#include <ctime>
int randIn(int low, int upper)//产生[low,upper]区间内的一个随机数
{//表示精度有限
if(low > upper){
int tmp = low;
low = upper;
upper = tmp;
}
return low + (upper-low+1)*rand()/RAND_MAX;
}
//区间[1,total]中随机取m个无重复数的Floyd算法
void randomFloyd(int m, int total, int* record) //递归算法
{
if(m == 0 || m>total) return;
randomFloyd(m-1, total-1, record);
int t = randIn(1, total);
if(!record[t]){
record[t] = 1; //record 使用前要初始化全部清零
}
else{
record[total] = 1;
}
}
void randomFloydFast(int m, int total, int* record) //非递归算法
{
if(m == 0 || m>total) return;
int t, i;
for(i = total - m + 1; i <= total; i++){
t = randIn(1, i);
if(!record[t]){
record[t] = 1;
}
else{
record[i] = 1;
}
}
}
void printRecord(int* record, int len)
{
int i;
for(i = 1; i <= len; i++){
if(record[i]){
printf("%d ", i);
}
}
printf("\n");
}
int main(void)
{
int total, m;
int *ans;
srand((unsigned int)time(0));
while(std::cin>>m>>total){ //测试
ans = new int[total+1];
memset(ans, 0, sizeof(int)*(total+1));
randomFloydFast(m, total, ans);
printRecord(ans, total);
delete []ans;
}
return 0;
}
//Floyd算法的正确性可以证明
参考:
《编程珠玑II》