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;
      }
      
  • 相关阅读:
    在MyEclipse中运行tomcat报错 严重: Error starting static Resources
    MyEclipse 2015 运行tomcat 内存溢出的解决方法
    (转)Tomcat内存设置详解
    Object调用控件的办法
    Hibernate主键生成方式之hilo
    (转)“中国第一程序员” 求伯君的传奇经历
    雷军相识求伯君
    (转)雷军重掌金山幕后:与求伯君暗战三年两次逼宫
    华军软件发展及盈利模式
    中年人编程
  • 原文地址:https://www.cnblogs.com/lr599909928/p/12924814.html
Copyright © 2011-2022 走看看