[kuangbin带你飞]专题十二 基础DP1
网址:https://cn.vjudge.net/contest/68966#problem/B
Ignatius and the Princess IV
HDU - 1029
"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?
"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?
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
3 5 1
没用dp,设置两个变量x,y。x存数,y存次数。每次输入一个数进行比较,如果与x相同,y++,如果不相同y--,若y为0,x变化,因为结果出现了(n+1)/2次,因此最后x一定为结果。
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 2147483647
int main()
{
int t;
int a;
int x,y;
while(scanf("%d",&t) != EOF){
y = 0;
x = -MAXN-1;
for(int i = 0;i < t;i++){
scanf("%d",&a);
if(a == x){
y++;
}
else if(y == 0){
x = a;
}
else{
y--;
}
}
printf("%d\n",x);
}
return 0;
}

本文介绍了一个算法问题,即从一组给定的整数中找出出现次数超过(n+1)/2的特殊整数,并提供了一种高效的解决方案。通过使用两个变量x和y来追踪可能的特殊整数及其出现频率。
422

被折叠的 条评论
为什么被折叠?



