算法设计例题:主元素(随机算法)
memory limit: 5000KB time limit: 1000MS
accept: 1 submit: 5
Description
设T[1:n]是一个含有n个元素的数组(集合)。当 | {i | T[i]=x} | > n/2 时,称元素x是数组T的主元素。
Input
第一行是一个正整数T,表示测试用例的个数。每个测试用例占两行,第一行是一个整数N( 0 < N < 100000 ),表示集合元素的个数,第二行是N个整数。
Output
为每个测试用例输出一行结果:如果该集合有主元素,输出该主元素,如果没有主元素,则输出 no 。
Sample Input
2
10
3 5 7 3 9 3 3 1 3 3
10
3 3 3 3 1 2 4 5 6 7
Sample Output
3
no
Author
John
解决方法:
#include<stdio.h>
#include<cstdlib>
#include<time.h>
#define N 200000
int x;
int a[N];//这个不能放在main()函数中,局部变量的数组不能开太大,不然提交的时候会出现"Runtime Error!"
bool b(int a[],int n)
{
int i=rand()%n+1;//产生从1~n之间的整数
x=a[i];
int count=0;
for(int j=1;j<=n;j++)
if(a[j]==x)
count++;
return (count>n/2);
}
bool majority(int a[],int n)
{
if(b(a,n))
return true;
else
return b(a,n);
}
int main()
{
srand((int)time(0));
int n,k=0,testNum;
scanf("%d",&testNum);
while(k!=testNum)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
if(majority(a,n))
printf("%d\n",x);
else
printf("no\n");
k++;
}
return 0;
}
//特别注意的是,当换成c++的输入输出方式提交时会出现"Time Limit Exceed"的提示,当改成C的输入输出方式时就可以通过了,由此可见C的输入输出方式比C++的节省时间