zoukankan      html  css  js  c++  java
  • Codeforces Round #479 (Div. 3) C. Less or Equal (排序,贪心)

    • 题意:有一个长度为\(n\)的序列,要求在\([1,10^9]\)中找一个\(x\),使得序列中恰好\(k\)个数满足\(\le x\).如果找不到\(x\),输出\(-1\).

    • 题解:先对这个序列排个序,然后首先要注意\(k=0\)的情况

      如果\(k=0\)并且序列中含有\(1\),那么我们无论如何都找不到比\(1\)小的数,输出\(-1\),如果不含\(1\),那么只要输出\(a[1]-1\)即可.

      如果\(k\ne 0\),那么我们要找前\(k\)个小的数(连续相等的数也算),所以我需要用桶来记录每个数出现的次数,然后遍历序列,累加每个数出现的次数,如果\(sum=k\),那么当前这个数就是我们要找的,如果\(sum>k\)的话,那么我们无论如何都找不到\(x\)(因为\(sum\)记录的是\(\le x\)的数目).

    • 代码:

      #include <iostream>
      #include <cstdio>
      #include <cstring>
      #include <cmath>
      #include <algorithm>
      #include <stack>
      #include <queue>
      #include <vector>
      #include <map>
      #include <set>
      #include <unordered_set>
      #include <unordered_map>
      #define ll long long
      #define fi first
      #define se second
      #define pb push_back
      #define me memset
      const int N = 1e6 + 10;
      const int mod = 1e9 + 7;
      using namespace std;
      typedef pair<int,int> PII;
      typedef pair<long,long> PLL;
       
      int n,k;
      int a[N];
      map<int,int> mp;
      int main() {
          ios::sync_with_stdio(false);cin.tie(0);
          cin>>n>>k;
           for(int i=1;i<=n;++i){
               cin>>a[i];
               mp[a[i]]++;
           }
       
           sort(a+1,a+1+n);
           if(k==0){
               if(mp[1]) puts("-1");
               else printf("%d\n",a[1]-1);
               return 0;
           }
           int cnt=0;
           for(auto w:mp){
               cnt+=w.se;
               if(cnt==k){
                   printf("%d\n",w.fi);
                   return 0;
               }
               if(cnt>k){
                   puts("-1");
                   return 0;
               }
           }
           puts("-1");
       
          return 0;
      }
      
  • 相关阅读:
    22(1).模型融合---Random Forest
    Tesseract 模块
    非线性问题的三种处理方法
    jupyter 快捷键
    回归评价指标---MSE、RMSE、MAE、R-Squared
    理解JavaScript中的事件处理
    jquery事件重复绑定解决办法
    IE6 IE7 IE8(Q) 不支持 JSON 对象
    浏览器事件机制与自定义事件的实现
    浏览器加载和渲染html的顺序
  • 原文地址:https://www.cnblogs.com/lr599909928/p/12924814.html
Copyright © 2011-2022 走看看