1 条题解

  • 0
    @ 2026-5-4 14:28:35

    在这个问题中,你可以采用以下方法:首先,将数组排序。

    ans 为答案。那么你有两种情况:

    • 如果 k=0k = 0,则 ans = a[0] - 1
    • 否则,ans = a[k-1](对于 00 索引的数组)

    然后你需要计算数组 aa 中小于或等于 ans 的元素个数,记为 cnt

    如果 ans < 1 或者 cnt ≠ k,则输出 "-1";否则输出 ans

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main() {
    #ifdef _DEBUG
    	freopen("input.txt", "r", stdin);
    //	freopen("output.txt", "w", stdout);
    #endif
    	
    	int n, k;
    	scanf("%d %d", &n, &k);
    	
    	vector<int> a(n);
    	for (int i = 0; i < n; ++i)
    		scanf("%d", &a[i]);
    	
    	sort(a.begin(), a.end());
    	
    	int ans;
    	
    	if (k == 0) {
    		ans = a[0] - 1;
    	} else {
    		ans = a[k - 1];
    	}
    	
    	int cnt = 0;
    	
    	for (int i = 0; i < n; ++i)
    		if (a[i] <= ans) ++cnt;
    	
    	if (cnt != k || !(1 <= ans && ans <= 1000 * 1000 * 1000)) {
    		puts("-1");
    		return 0;
    	}
    	
    	printf("%d\n", ans);
    	
    	return 0;
    }
    
    • 1

    信息

    ID
    6788
    时间
    1000ms
    内存
    256MiB
    难度
    5
    标签
    递交数
    1
    已通过
    1
    上传者