快排模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

const int N=1E6+10;
int n,q[N];

void quick_sort(int q[],int l,int r){
if(l>=r) return;

int x=q[(l+r)/2],i=l-1,j=r+1;
while(i<j){
do i++;while(q[i]<x);
do j--;while(q[j]>x);
if(i<j) swap(q[i],q[j]);
}

quick_sort(q,l,j);
quick_sort(q,j+1,r);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);

quick_sort(q,0,n-1);

for(int i=0;i<n;i++) printf("%d ",q[i]);

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<algorithm>
using namespace std;

const int N = 1e6+10;
int n, k;
int q[N];

int quick_sort(int l, int r, int k) {
if (l == r) return q[l];


int x = q[(l + r) / 2], i = l - 1, j = r + 1;

while(i < j) {
do { i++; } while (q[i] < x);
do { j--; } while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}

int s1 = j - l + 1;
if (k <= s1) return quick_sort(l, j, k);
return quick_sort(j + 1, r, k - s1);

}

int main() {
cin >> n >> k;

for (int i = 0; i < n; i++) cin >> q[i];

cout << quick_sort(0, n - 1, k) << endl;

return 0;

}

acw786.第k个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
using namespace std;

const int N=1e6+10;
int n,k;
int q[N];

int main(){
cin>>n>>k;
for(int i=0;i<n;i++) scanf("%d",&q[i]);
while(k--){
int x;
cin>>x;


int l=0,r=n-1;
while(l<r){
int mid=(l+r)>>1;
if(q[mid]>=x) r=mid;
else l=mid+1;
}

if(q[l]!=x) cout<<"-1 -1"<<endl;
else{
cout<<l<<' ';
int l=0,r=n-1;
while(l<r){
int mid=(l+r+1)>>1;
if(q[mid]<=x) l=mid;
else r=mid-1;
}
cout<<l<<endl;
}
}
}

acw.789 数的范围–二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
using namespace std;

const int N=1e6+10;
int n,k;
int q[N];

int main(){
cin>>n>>k;
for(int i=0;i<n;i++) scanf("%d",&q[i]);
while(k--){
int x;
cin>>x;


int l=0,r=n-1;
while(l<r){
int mid=(l+r)>>1;
if(q[mid]>=x) r=mid;
else l=mid+1;
}
if(q[l]!=x) cout<<"-1 -1"<<endl;
else{
cout<<l<<' ';
int l=0,r=n-1;
while(l<r){
int mid=(l+r+1)>>1;
if(q[mid]<=x) l=mid;
else r=mid-1;
}
cout<<l<<endl;
}
}
return 0;

}