这是一道简单的题, 但是因为知识点漏洞卡了半天, 难受死了!!!!!!!
/* B. Moamen and k-subarrays */
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define inf 0x3f3f3f3f
using namespace std;
int main(int argc, char const *argv[]) {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while(T --) {
int n, k;
cin >> n >> k;
vector<int > v(n+1);
vector<int > v1(n+1);
for(int i = 0; i < n; i ++) {
cin >> v[i];
v1[i] = v[i];
}
sort(v.begin(), v.end());
int cnt = 1;
for(int i = 0; i < n-1; i ++) {
int temp = upper_bound(v.begin(), v.end(), v1[i])-v.begin();
if(v1[i+1] != v[temp] || v1[i] > v1[i+1]) {
cnt++;
}
}
if(cnt <= k) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
return 0;
}
这段代码看似正确其实,会有边界问题, 就是开数组是vector<int > v(n+1) 后, 使用的v.end() 相当于v+n+1, 所以排序时要注意v.end()-1;
AC题解:
/* B. Moamen and k-subarrays */
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define inf 0x3f3f3f3f
using namespace std;
int main(int argc, char const *argv[]) {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while(T --) {
int n, k;
cin >> n >> k;
vector<int > v(n+1);
vector<int > v1(n+1);
for(int i = 0; i < n; i ++) {
cin >> v[i];
v1[i] = v[i];
}
sort(v.begin(), v.end()-1);
int cnt = 1;
for(int i = 0; i < n-1; i ++) {
int temp = upper_bound(v.begin(), v.end()-1, v1[i])-v.begin();
if(v1[i+1] != v[temp] || v1[i] > v1[i+1]) {
cnt++;
}
}
if(cnt <= k) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
return 0;
}