目录
汉诺塔问题
#include <stdio.h>
void Move(int n, char start, char goal,char temp)
{
if(n >= 1)
{
Move(n-1, start, temp, goal);
printf("%c -> %c\n", start, goal);
Move(n-1, temp, goal, start);
}
}
int main()
{
int n;
scanf("%d", &n);
char a = 'a' , b = 'b', c = 'c';
Move(n, a, c, b);
return 0;
}
求一组数中的第K大数
输入
9
6 5 9 8 2 1 7 3 4
5
输出
5
输入
9
6 5 9 8 2 1 7 3 4
7
输出
3
#include <stdio.h>
#include <stdlib.h>
void swap(int *x, int *y);
int FindKthLargest(int s[], int K, int Left, int Right);
int main()
{
int N;
scanf("%d", &N);
int *s;
s = (int *)malloc(sizeof(int) * N);
int i;
for(i = 0; i < N; i++)
{
scanf("%d", &s[i]);
}
int K;
scanf("%d", &K);
printf("%d",FindKthLargest(s, K, 0, N-1));
return 0;
}
void swap(int *x, int *y)
{
int t;
t = *x; *x = *y; *y = t;
}
int FindKthLargest(int s[], int K, int Left, int Right)
{
int e = s[Left];
int L = Left, R = Right;
while(1)
{
while(s[Left] >= e) Left++;
while(s[Right] < e) Right--;
if(Left < Right) swap(&s[Left], &s[Right]);
else break;
}
swap(&s[L], &s[Left-1]);
if((Left-L) > K)
return FindKthLargest(s, K, L, Left-2);
else if((Left-L) < K)
return FindKthLargest(s, K-(Left-L), Left, R);
else return e;
}