ZOJ-2132-The MostFrequent Number
Time Limit: 5 Seconds Memory Limit: 1024 KB
Seven (actuallysix) problems may be somewhat few for a contest. But I am really unable todevise another problem related to Fantasy Game Series. So I make up an veryeasy problem as the closing problem for this contest.
Given a sequenceof numbers A, for a number X if it has the most instances (elements of the samevalue as X) in A, then X is called one of the most frequent numbers of A. Now asequence of numbers A of length L is given, and it is assumed that there is anumber X which has more than L / 2 instances in A. Apparently X is the only onemost frequent number of A. Could you find out X with a very limited memory?
Input
Input containsmultiple test cases. Each test case there is one line, which starts with anumber L (1 <= L <= 250000), followed by L numbers (-2^31 ~ 2^31-1).Adjacent numbers is separated by a blank space.
Output
There is one line foreach test case, which is the only one most frequent number X.
Sample Input
5 2 1 2 3 2
8 3 3 4 4 4 4 3 4
Sample Output
2
4
0x01 题意
求序列众数。
0x02 分析
第一次是在啊哈算法最后一章学到的,书中给出复杂度逐次降低的算法。
大致意思是,因为最多的数超过一半,例如第一个sample中,2众数,可以将每个2都分配给不同的其它元素,最后2还是有剩余,就像是同归于尽一样,最后剩下的就是其中最多的元素了。利用这个我们可以定义一个当前数和当前数的个数下一个比,相同则加一,不同则减一知道个数为0时,当前数变成下一个,知道输入结束,存活下来的就是众数。
0x03 Code
一遍AC:
//ZOJ-2132 //2017-06-18 #include<bits/stdc++.h> int n, num; int main() { while(scanf("%d%d", &n, &num)!=EOF) { int cnt = 1; for (int i = 2; i <= n; i++) { int tmp; scanf("%d", &tmp); if (cnt == 0) { cnt = 1; num = tmp; continue; } if (tmp == num) cnt++; else cnt--; } printf("%d\n", num); } return 0; }