Codeforces Beta Round #63 (Div. 2) E. Subsegments(map + set)

原題鏈接:https://codeforces.com/contest/69/problem/E


Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in , which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem.

Input
The first line contains two positive integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ n) — the number of array elements and the length of the segment.

Then follow n lines: the i-th one contains a single number ai ( - 109 ≤ ai ≤ 109).

Output
Print n–k + 1 numbers, one per line: on the i-th line print of the maximum number of those numbers from the subarray ai ai + 1 … ai + k - 1 that occur in this subarray exactly 1 time. If there are no such numbers in this subarray, print “Nothing”.

輸入1:

5 3
1
2
2
3
3

輸出1:

1
3
2

輸出2:

6 4
3
3
3
4
4
2

輸出2:

4
Nothing
3

題意: 給一個長度爲 n 的數組,輸出 n-k-1 個數,分別爲下標爲 i 到 i+k-1 這個區間內存在且只出現一次的數的最大值,不存在則輸出 “Nothing”。

思路:

  1. 該題可以用線段樹來做也可以用STL來做,這裏用STL解答。
  2. 先把前 k 個數只出現一次的數存入 set 集合裏,自動從小到大排序,如果不爲空則輸出最後一個數,否則輸出 “Nothing”。
  3. 然後從 k+1 開始,每加入一個數就刪去上一個區間的第一個數,並判斷刪去的數剩下的個數是否爲 1,若是,則加入可行集合 set 裏,否則就看它是否在可行集合裏,在的話就刪掉。
  4. 然後再判斷新加入的數的個數是否爲 1,是的話加入可行集合裏,否則就看它是否在可行集合裏,在的話就刪掉。
  5. 最後再判斷該區間的可行集合裏是否爲空,爲空的話就輸出 “Nothing”,否則輸出最後一個數。

【總結】C++ 基礎數據結構 —— STL之集合(set)用法詳解
【總結】C++ 基礎數據結構 —— STL之關聯容器(map)用法詳解

Code:

#include <iostream>
#include <map>
#include <set>
using namespace std;
const int N=1e5+100;
map<int,int> mp;
set<int> s;
int a[N];
int main()
{
    int n,k;    cin>>n>>k;
    for(int i=1;i<=n;i++)   cin>>a[i];
    for(int i=1;i<=n;i++){
        if(i<=k){
            mp[a[i]]++;
            if(mp[a[i]]==1) s.insert(a[i]);
            else{
                if(s.find(a[i])!=s.end())
                    s.erase(a[i]);
            }
            if(i==k){
                if(s.empty())   cout<<"Nothing"<<endl;
                else    cout<<*(--s.end())<<endl;
            }
        }
        else{
            mp[a[i]]++;
            mp[a[i-k]]--;
            if(mp[a[i]]==1) s.insert(a[i]);
            else{
                if(s.find(a[i])!=s.end())
                    s.erase(a[i]);
            }
            if(mp[a[i-k]]==1)   s.insert(a[i-k]);
            else{
                if(s.find(a[i-k])!=s.end())
                    s.erase(a[i-k]);
            }
            if(s.empty())   cout<<"Nothing"<<endl;
            else    cout<<*(--s.end())<<endl;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章