1. 程式人生 > >(第四場)G Maximum Mode 【YY+暴力】

(第四場)G Maximum Mode 【YY+暴力】

i++ ase line printf getchar() inpu 需要 題解 ring

鏈接:https://www.nowcoder.com/acm/contest/142/G

來源:牛客網

題目描述

The mode of an integer sequence is the value that appears most often. Chiaki has n integers a1,a2,...,an. She woud like to delete exactly m of them such that: the rest integers have only one mode and the mode is maximum.

輸入描述:

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m < n) -- the length of the sequence and the number of integers to delete.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) denoting the sequence.
It is guaranteed that the sum of all n does not exceed 106.

輸出描述:

For each test case, output an integer denoting the only maximum mode, or -1 if Chiaki cannot achieve it.

case:

input:

5
5 0
2 2 3 3 4
5 1
2 2 3 3 4
5 2
2 2 3 3 4
5 3
2 2 3 3 4
5 4
2 2 3 3 4

output:

-1
3
3
3
4

題目大意:

給N個數, 刪掉M個數,使得剩下的數眾數最大,求那個眾數。

官方題解:

?枚舉答案,考慮需要刪?幾個數才能使之變成眾數

?出現次數多余它的都要被刪到次數比它小

?剩下的隨便便刪

大概思路(本人理解):

枚舉出現的次數,因為出現次數多的更有可能成為眾數,所以從多到少枚舉出現的次數,其次就是相同出現次數的話取最大的那個(也有可能是由比它出現多的減過來的),簡單來說就是用M次刪除把最大的那個眾數弄出來。

不過要註意一點就是:優化輸入!!!本人沒有優化輸入前TLE了五次,當然,這裏包括了更傻的每個案例都重新定義映射和動態數組,想這樣省略初始化,但是太慢了。。。還是老老實實初始化的好。(哎,都在代碼裏了)

AC code:

技術分享圖片
#include <map>
#include <vector>
#include <cstdio>
#include 
<cstring> #include <iostream> #include <algorithm> #define INF 0x3f3f3f3f #define ll long long int using namespace std; const int MAXN = 1e5+10; ll a[MAXN]; ///原序列 ll c[MAXN]; ///c[x]出現次數為 X 的最大值 ll T_case, N, K; vector<ll> num_len[MAXN]; ///出現次數為 X 的數有多少個 map<ll, ll> mmp; ///記錄出現次數 inline ll read() ///優化輸入 { register ll c = getchar(), flag = 1, sum = 0; while(c > 9 || c < 0) { if(c == -) flag = -1; c = getchar(); } while(c <= 9 && c >= 0) { sum = sum*10+c-0; c = getchar(); } return flag*sum; } int main() { scanf("%lld", &T_case); while(T_case--) { N = read(); K = read(); mmp.clear(); for(ll i = 0; i <= N; i++) { num_len[i].clear(); c[i] = 0; } for(int i = 1; i <= N; i++) { a[i] = read(); if(mmp.count(a[i]) == 0) mmp[a[i]] = 1; else mmp[a[i]]++; } for(int i = 1; i <= N; i++) { ll x = mmp[a[i]]; ///a[i]出現的次數 if(x) { num_len[x].push_back(a[i]); ///增加出現次數為 x 的元素 c[x] = max(c[x], a[i]); ///更新出現次數為 X 的最大值 mmp[a[i]] = 0; ///出現次數清零,避免重復加 } } ll res = -1; ///當前滿足成為眾數的最大值 ll pre = 0; ///使當前的數成為眾數的需要的刪除次數 ll ans = -1; ///答案 for(int len = N; len > 0; len--) ///枚舉出現次數 { ll xx = num_len[len].size(); ///出現次數為len的數量 pre+=xx; if(xx) { res = max(res, c[len]); ///當前的眾數有可能由上一個眾數退化而來 if(pre-1 <= K) ///如果剩余的刪除次數滿足需要刪除次數的條件 { ans=max(ans, res); ///更新答案 } else break; ///剩余的刪除次數無法滿足當前長度眾數的要求的,那之後的也無法滿足了 } K-=pre; if(K<0) break; ///無剩余操作次數 } printf("%lld\n", ans); } return 0; }
View Code

(第四場)G Maximum Mode 【YY+暴力】