【HDOJ_1029】Ignatius and the Princess IV

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1029

大意是,有一个数列,有N个数,N为奇数,有一个数出现的次数>=(N+1)/2,现在要求出这个特殊的数来.

思路:

思路1.遍历并记录每个数出现的次数,找到次数>=(N+1)/2对应的那个数即可,记录次数的时候有点类似桶排序.

思路2.对这个数列进行排序,由于它出现的次数>=(N+1)/2,所以排序过后,这个数不可能全在左边,或全在右边,中位数的位置一定是这个特殊的数.

思路3.注意N为奇数,所以,特殊数的次数>其余所有数的次数之和,因此遇到两个相同的数就消去,则剩余的数列中,这个特殊的数出现的次数仍然是>=(N-2+1)/2的.


思路1代码:可以AC

#include <stdio.h>

#define maxn 65535+1
int N, i, j, x;

int main()
{
	//freopen("in.txt", "r", stdin);
	while(scanf("%d", &N)!=EOF)
	{
		int a[maxn]={0};
		for(i=0;i<N;i++)
		{
			scanf("%d", &x);
			a[x] ++;	//to store times the number x appears.
		}
		for(i=0;i<maxn;i++)
			if(a[i]>=(N+1)/2)
			{
				printf("%d\n", i);
				break;
			}
	}

	return 0;
}

思路2代码:超时,不能AC

#include<stdio.h>

int N, i, a[65535+1];

void bin_sort(int a[], int N)	//sort algorithm
{
	for(int i=0;i<N;i++)
	{
		int x = a[i];
		int low = 0, high = i-1;
		while(low<=high)
		{
			int mid = (low+high) / 2;
			if(x<a[mid])
				high = mid - 1;
			else
				low = mid + 1;
		}
		for(int j=i;j>low;j--)
			a[j] = a[j-1];
		a[low] = x;
	}
}

int main()
{
	//reopen("in.txt", "r", stdin);
	while(scanf("%d", &N)!=EOF)
	{
		for(int i=0;i<N;i++)
			scanf("%d", &a[i]);
		bin_sort(a, N);
		
		printf("%d\n", a[(N+1)/2]);
	}

	return 0;
}

思路3

不懂

代码如下

    #include<iostream>  
    #include<stdio.h>  
    using namespace std;  
      
    int main()  
    {  
        int cnt, max, cur, n;  
        while(scanf("%d", &n) != EOF)  
        {  
            cnt = 0;  
            for(int i=0; i<n; i++)  
            {  
                scanf("%d", &cur);  
                if(!cnt)  
                {  
                    max = cur;  
                    cnt ++;  
                }  
                else if(cur != max) cnt --;  
                else if(cur == max) cnt ++;  
            }  
            //cout << max << endl;  
            printf("%d\n", max);  
        }  
        return 0;  
    }  

猜你喜欢

转载自blog.csdn.net/ten_sory/article/details/79786065