E - Ignatius and the Princess IV

####E - Ignatius and the Princess IV
“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.

“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.

“But what is the characteristic of the special integer?” Ignatius asks.

“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…” feng5166 says.

Can you find the special integer for Ignatius?
Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.
Output
For each test case, you have to output only one line which contains the special number you have found.
Sample Input
5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1
Sample Output
3
5
1
####分析:
因为有内存限制,所以用几个大数组储存数据并且进行运算是行不通的(如:a[i]=k) ,因此改变策略:输入的n个数中 每个数都看作是一个位置信息(如a[k]++),通过置零该数组解决循环问题
####代码实现:

/*
错误代码: 
#include<iostream>
#include<cstdio>
long a[1000000] = {0} ;

using namespace std ;

int main ()
{
	long n , i , d , ; //最好用配套的long 
	while (scanf( "%d" , &n ) != EOF ){

	for ( i = 0 ; i < n ; i++ )
	{// 数组第一个循环后没有被清空 导致第二个循环里的数组不全为0 
		cin >> d ;
		a[d]++ ;
		if ( a[d] >= (n+1)/2 )
		{cout << d << endl  ;break ; 
//		a[1000000] = {0} ;  //在这里遍历long不好使 
		}
	}
  }
	

	return 0 ;
 }
*/
//正确代码: 
#include<iostream>
#include<cstdio>
#include<string.h>
long a[1000000] = {0}; //在外面定义 在里面赋值 
using namespace std ;
int main()
{
	long n,i,t,re;  //配套long 
	while(scanf("%ld",&n)!=EOF)
	//在int main 里定义大数组不好使 
	{   memset(a,0,1000000);   //memset  把数组a 前1000000个值赋值0   如果用在整型数组里 只能赋值0或-1. 
		for(i=0;i<n;i++)
		{
			scanf("%ld",&t);
			a[t]++;
			if(a[t]>=(n+1)/2)
			{
				re = t ;
			}			
		}
		printf("%ld\n",re);
	}
} 
/*
教训: 
1:由于long型数组太大 无法在int main 里初始化  这就导致了前一个循环完成后,在后一个循环里数组的数不全为0 , 所以要用memset去初始化 
2:如果不用re代替t 则可能出现的情况中  输入的数字都相同  那么结果会提前输出 所以要建立一个中间变量去储存该值  
*/ 
发布了27 篇原创文章 · 获赞 16 · 访问量 1987

猜你喜欢

转载自blog.csdn.net/weixin_43899069/article/details/98115356