hdu 1029 Ignatius and the Princess IV
Ignatius and the Princess IV
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32767 K (Java/Others)
Total Submission(s): 30075 Accepted Submission(s):
12837
"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?
我们按照序列依次扫描,先把第一个x的值给flag
计数器num++ 然后向右扫描
如果输入的x跟flag相同 那num就++,不同,就 --,
一直重复下去,到了最后flag就是我们想要的那个多元素。
下面是代码:
#include <stdlib.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while(~scanf("%d",&n))
{
int num=0,flag,x;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
if(num==0)
{
num++;
flag=x;
}
else if(flag==x)
{
num++;
}
else
{
num--;
}
}
printf("%d\n",flag);
}
return 0;
}
出处:https://www.cnblogs.com/52why
微信公众号: 红雨python
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步