一开始没搞懂题目是想干什么,于是写了一个扫一遍的代码,A了,如下:
代码:
1 #include <iostream> 2 3 using namespace std; 4 5 int main() { 6 int N, K, a; 7 bool found = false; 8 int lt = 0; 9 10 scanf("%d%d", &N, &K); 11 for (int i = 0; i < N; i++) { 12 scanf("%d", &a); 13 if (a == K) 14 found = true; 15 if (a < K) 16 lt++; 17 } 18 printf("%d\n", (found ? lt + 1 : -1)); 19 20 return 0; 21 }
做到后面一题的时候才明白题目是什么意思,代码如下:
1 #include <iostream> 2 3 using namespace std; 4 5 #define SIZE 100000 6 7 int N, K; 8 int a[SIZE]; 9 10 int ltc(int left, int right) { 11 if (left >= right) 12 return 0; 13 14 int l = left; 15 int r = right; 16 int p = a[left]; 17 18 while (l < r) { 19 while (l < r && a[r] > p) 20 r--; 21 a[l] = a[r]; 22 while (l < r && a[l] < p) 23 l++; 24 a[r] = a[l]; 25 } 26 a[l] = p; 27 28 if (a[l] == K) 29 return l - left; 30 else if (a[l] < K) 31 return l - left + 1 + ltc(l + 1, right); 32 else 33 return ltc(left, l - 1); 34 } 35 36 int main() { 37 bool found = false; 38 39 scanf("%d%d", &N, &K); 40 for (int i = 0; i < N; i++) { 41 scanf("%d", &(a[i])); 42 found |= (a[i] == K); 43 } 44 45 printf("%d\n", (found ? ltc(0, N - 1) + 1: -1)); 46 47 return 0; 48 }
时间: 2024-12-27 17:21:43