-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsubsequence.c
81 lines (64 loc) · 1.75 KB
/
subsequence.c
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// do wyrzucenia - podciąg, a nie podzbiór
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int index = partition(arr, low, high);
quick_sort(arr, low, index - 1);
quick_sort(arr, index + 1, high);
}
}
// check if b[] contains all elements of a[]
bool is_subsequence(int a[], int size_a, int b[], int size_b) {
quick_sort(a, 0, size_a - 1);
quick_sort(b, 0, size_b - 1);
int j = 0;
for (int i = 0; i < size_a; i++) {
if (a[i] < b[j])
return false;
else if (a[i] > b[j])
i--;
j++;
if (j > size_b) return false;
}
return true;
}
int main() {
int size_a, size_b;
if (!scanf("%d", &size_a)) printf("invalid value");
int* a = (int*)malloc((size_t)size_a * sizeof(int));
for (int i = 0; i < size_a; i++) {
if (!scanf("%d", &a[i])) printf("invalid value");
}
if (!scanf("%d", &size_b)) printf("invalid value");
int* b = (int*)malloc((size_t)size_b * sizeof(int));
for (int i = 0; i < size_b; i++) {
if (!scanf("%d", &b[i])) printf("invalid value");
}
// int a[6] = {1, 2, 30, 4, 5, 6};
// int b[7] = {-1, 6, 2, 30, 4, 5, 1};
// size_a = 6;
// size_b = 7;
printf("%d", is_subsequence(a, size_a, b, size_b));
free(a);
free(b);
return 0;
}