您的位置:首页 > 其它

HDU1029(去掉两个不同的数序列中出现频率最多的那个数不变)DP2

2017-12-30 12:56 309 查看
题目链接

题目要求:找出一个序列中出现频率大于(n+1)/2的那个数字

AC代码

/*第一种方法就是对于一个序列来说
如果我们每次去掉两个不同的数,该序列中
出现频率最多的那个数是不变的
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n;
while(~scanf("%d",&n))
{
int cnt=0,res;
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
if(cnt==0)
{
res=x;
cnt++;
}
else
{
if(res==x)
cnt++;
else
cnt--;
}

}
printf("%d\n",res);
}
return 0;
}
/*第二种方法就是排序,
找出数组中出现次数超过一半的元素
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e8+5;
int a[maxn];
int main()
{
int n;
while(~scanf<
4000
/span>("%d",&n))
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
printf("%d\n",a[(n+1)/2]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐