统计数字

NOIP2007 Problem1

Method 1:

基本思路:
数字范围很大,个数很少,马上想到"离散化"
先排序,然后重新赋值,统计
这样做没有问题,只是转念一想,好像完全可以借助 lower _ bound,upper _ bound 直接统计数量,,,嗯,好像是的

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAXN=2e5+1;
int A[MAXN];
inline int read()
{
	int f=1,x=0;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
	return f*x;
}
int main()
{

	memset(A,0,sizeof(A));
	int n=read();
	for(int i=1;i<=n;i++)
	{
		A[i]=read();
	}
	sort(A+1,A+n+1);

	if(A[n]==0)
	{
		printf("%d %d",A[n],n);
		return 0;
	}
	for(int i=1,m=A[1];i<=n+1;i++)
	{
		if(A[i]!=m)
		{
			m=A[i];
			int W=upper_bound(A+1,A+n+1,A[i-1])-lower_bound(A+1,A+n+1,A[i-1]);
			printf("%d %d\n",A[i-1],W);
		}
	}
	return 0;
}

Method 2:

直接上 $Map $ 就好了!啥事都不必干了!

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
typedef pair<int,int> pii;
typedef map<int,int>::iterator miii;
map<int,int>m;
inline int read()
{
    int f=1,x=0;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return f*x;
}
int main()
{
    int n=read();
    for(int i=1;i<=n;i++)
    {
        int x=read();
        if(!m.count(x))m.insert(pii{x,1});
        else m[x]++;
    }
    for(miii it=m.begin();it!=m.end();it++)
    {
        printf("%d %d\n",it->first,it->second);
    }
    return 0;
}

posted @ 2018-07-20 20:14  昤昽  阅读(181)  评论(0编辑  收藏  举报