[TYVJ] P1001 第K极值

第K极值

 
背景 Background
成成第一次模拟赛 第一道
  
描述 Description
给定一个长度为N(0<n<=10000)的序列,保证每一个序列中的数字a[i]是小于maxlongint的非负整数 ,编程要求求出整个序列中第k大的数字减去第k小的数字的值m,并判断m是否为质数。(0<k<=n)
 
输入格式 InputFormat
输入格式:
第一行为2个数n,k(含义如上题)
第二行为n个数,表示这个序列
 
输出格式 OutputFormat
输出格式:
如果m为质数则
第一行为'YES'(没有引号)
第二行为这个数m
否则 
第一行为'NO'
第二行为这个数m
 
 
 
 
样例输入 SampleInput [复制数据

5 2
1 2 3 4 5

 
样例输出 SampleOutput [复制数据]

YES
2

数据范围和注释 Hint
对于第K大的详细解释:
如果一个序列为1 2 2 2 2 3
第1大 为3
第2大 为2
第3大 为2
第4大 为2
第5大 为1
第K小与上例相反

另外需要注意的是
最小的质数是2,如果小于2的话,请直接输出NO

 
题解
 1 #include<stdio.h>
 2 #include<math.h>
 3 int
 4     a[10000];
 5 void
 6 qsort(int head,int tail)
 7 {
 8     int i,j,x;
 9     
10     i=head;j=tail;
11     x=a[head];
12     while(i<j)
13     {
14         while((i<j)&&(a[j]>=x)) j--;
15         a[i]=a[j];
16         while((i<j)&&(a[i]<=x)) i++;
17         a[j]=a[i];
18     }
19     a[i]=x;
20     if (head<(i-1)) qsort(head,i-1);
21     if ((i+1)<tail) qsort(i+1,tail);
22 }
23 
24 int
25 check(int n)
26 {
27     int i;
28     if (n==2) return(1);
29     
30     for (i=2;i<=(n-1);i++)
31     if (n%i==0) return(0);
32     
33     return(1);
34 }
35 
36 int 
37 main(void)
38 {
39     int i,n,k,p;
40     scanf("%d%d
",&n,&k);
41     for (i=1;i<=n;i++)
42     scanf("%d",&a[i]);
43     qsort(1,n);
44     
45     p=a[n-k+1]-a[k];
46     if (p<2) printf("NO
%d",p);
47     else
48     {
49        if (check(p)==0) printf("NO
%d",p);
50       else printf("YES
%d",p);
51     }
52     return 0;
53 }
原文地址:https://www.cnblogs.com/sxiszero/p/3588506.html