传说有一道很Boring的题目:
Description
集合的前N个元素:编一个程序,按递增次序生成集合M的最小的N个数,M的定义如下:
(1)数1属于M;
(2)如果X属于M,则Y=2*X+1和Z=3*x+1也属于M;
(3)此外再没有别的数属于M。
Input
n(b.in) (1≤n≤100)
Output
生成集合M的最小的N个数(b.out)
看到集合问题,本人就马上用set了,代码如下:
#include <set>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
set<int> s;
int n,i;
cin>>n;
s.insert(1);
int p1,p2;
set<int>::iterator ite=s.begin();
for(i=1; i<=n; i+=2){
s.insert( 2 * (*ite) + 1);
s.insert( 3 * (*ite) + 1);
ite++;
}
for( i=1, ite = s.begin(); ite!=s.end() && i <= n; ite++, i++){
cout<<*ite<<' ';
}
cout<<endl;
return 0;
}
自认为很完美,提交结果是Wrong Answer。艹,大骂评测系统,竟敢怀疑STL的正确性!于是要来童鞋过了的代码,如下:
#include <iostream>
using namespace std;
int a[1000]={0}, b[1000]={0}, head_a = 1, head_b = 1, rear = 1, x = 1, n;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cout << x << " ";
a[rear] = 2 * x + 1;
b[rear] = 3 * x + 1;
// cout << a[rear] << " " << b[rear] << " " << rear << endl;
rear++;
if (a[head_a] > b[head_b]) x = b[head_b], head_b++;
else if (a[head_a] < b[head_b]) x = a[head_a], head_a++;
else if (a[head_a] == b[head_b]) {
x = a[head_a];
head_a++;
head_b++;
}
}
return 0;
}
输入100, 结果我用STL写的得到:
1 3 4 7 9 10 13 15 19 21 22 27 28 31 39 40 43 45 46 55 57 58 63 64 67 79 81 82 85 87 91 93 94 111 115 117 118 121 127 129 130 135 136 139 159 163 165 166 171 172 175 183 187 189 190 193 202 223 231 235 237 238 243 244 247 255 256 259 261 262 271 273 274 279 280 283 319 327 331 333 334 343 345 346 352 355 364 382 388 391 406 409 418 478 490 496 499 514 517
还是输入100,童鞋的代码得到:
1 3 4 7 9 10 13 15 19 21 22 27 28 31 39 40 43 45 46 55 57 58 63 64 67 79 81 82 85 87 91 93 94 111 115 117 118 121 127 129 130 135 136 139 159 163 165 166 171 172 175 183 187 189 190 193 202 223 231 235 237 238 243 244 247 255 256 259 261 262 271 273 274 279 280 283 319 327 331 333 334 343 345 346 351 352 355 364 367 375 379 381 382 387 388 391 405 406 409 418
发现前面都是很相似的,但在352的地方突然变化了~
你能发现这个错误吗~