-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem41.c
More file actions
79 lines (66 loc) · 1.65 KB
/
problem41.c
File metadata and controls
79 lines (66 loc) · 1.65 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LINE 10000
int countNumbers(char *line){
int count = 0, inNumber = 0;
for(int i = 0; line[i]; i++){
if (isdigit(line[i])){
if (!inNumber){
count++;
inNumber = 1;
}
} else if (isspace(line[i])){
inNumber = 0;
}
}
return count;
}
int* parseTickets(char *line, int *n){
*n = countNumbers(line);
if (*n == 0){
printf("No tickets entered.\n");
exit(1);
}
int *arr = (int *)malloc((*n) * sizeof(int));
if (!arr){
printf("Memory allocation failed.\n");
exit(1);
}
int index = 0;
char *token = strtok(line, " ");
while (token){
arr[index++] = atoi(token);
token = strtok(NULL, " ");
}
return arr;
}
int calculateTime(int *tickets, int n, int k){
int time = 0;
for (int i = 0; i < n; i++){
if (i <= k)
time += (tickets[i] < tickets[k]) ? tickets[i] : tickets[k];
else
time += (tickets[i] < tickets[k]) ? tickets[i] : (tickets[k] - 1);
}
return time;
}
int main(){
char input[MAX_LINE];
int n, k;
printf("Enter the no of tickets array:\n");
fgets(input, sizeof(input), stdin);
int *tickets = parseTickets(input, &n);
printf("Enter k(target visitor) = ");
scanf("%d", &k);
if (k < 0 || k >= n){
printf("Invalid index k.\n");
free(tickets);
return 1;
}
int result = calculateTime(tickets, n, k);
printf("Total time = %d seconds\n", result);
free(tickets);
return 0;
}