yusijia’s blog timu 1

Contents

题目大意:

输入n个数,找出某个数的自然数下标

思路:

  • 快速排序
  • 二分查找
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
37
38
39
40
41
42
43
44



#include<stdlib.h>
struct in{
int sort;
int data;
}p[1000000];
int (const void*a,const void*b)
{
return ((const struct in*)a)->data-((const struct in*)b)->data; //a里的值(data)减b里的值
} //注意这里要用括号把*a抱起来,这是个指向函数的指针
int main()
{
int i,r,l,m,n,k,h;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&p[i].data);
p[i].sort=i;
}
qsort(p,n,sizeof(struct in),cmp);
scanf("%d",&h);
while(h--)
{
scanf("%d",&k);
l = 0;
r = n - 1;
while (l <= r)
{
m = (l+r) / 2;
if (p[m].data < k)
l = m + 1;
else if (p[m].data > k)
r = m - 1;
else break;
}
if (r < l)
puts("-1");
else
printf("%dn", p[m].sort + 1);
}
return 0;
}