| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
关于随机的一个诡异问题,求大神解释~这个题里边,如果加srand((int)time(0))这句话的话会导致RE,如果不加直接随机rand的话就可以AC,求解释~
RE代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <cstring>
using namespace std;
struct node
{
int w, lab;
}c[200];
int k, n;
int cmp(const node &a, const node &b)
{
return a.w < b.w;
}
int main()
{
int i, a, b, sa, sb, level;
bool flag = false;
scanf("%d", &k);
n = 3*k;
for(i = 0; i < n; i++)
{
scanf("%d", &c[i].w);
c[i].lab = i+1;
}
sort(c, c+n, cmp);
sa =sb = 0;
for(i = k; i < k+k; i++) sa += c[i].w;
for(i = k+k; i < n; i++) sb += c[i].w;
level = 1000*k;
if(sa*2>level && sb*2>level) flag = true;
srand((int)time(0));
while(!flag)
{
a = rand()%k+k;
b = rand()%k+(k<<1);
sa = sa - c[a].w+c[b].w;
sb = sb - c[b].w+c[a].w;
swap(c[a], c[b]);
if(sa*2>level && sb*2>level)
{
flag = true;
break;
}
}
for(i = 0; i < n; i++) printf("%d\n", c[i].lab);
return 0;
}
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <cstring>
using namespace std;
struct node
{
int w, lab;
}c[200];
int k, n;
int cmp(const node &a, const node &b)
{
return a.w < b.w;
}
int main()
{
int i, a, b, sa, sb, level;
bool flag = false;
scanf("%d", &k);
n = 3*k;
for(i = 0; i < n; i++)
{
scanf("%d", &c[i].w);
c[i].lab = i+1;
}
sort(c, c+n, cmp);
sa =sb = 0;
for(i = k; i < k+k; i++) sa += c[i].w;
for(i = k+k; i < n; i++) sb += c[i].w;
level = 1000*k;
if(sa*2>level && sb*2>level) flag = true;
while(!flag)
{
a = rand()%k+k;
b = rand()%k+(k<<1);
sa = sa - c[a].w+c[b].w;
sb = sb - c[b].w+c[a].w;
swap(c[a], c[b]);
if(sa*2>level && sb*2>level)
{
flag = true;
break;
}
}
for(i = 0; i < n; i++) printf("%d\n", c[i].lab);
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator