-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster.c
More file actions
122 lines (113 loc) · 1.97 KB
/
cluster.c
File metadata and controls
122 lines (113 loc) · 1.97 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <stdlib.h>
typedef struct Two
{
int index, v;
} Two;
typedef struct PriorityQueue
{
struct Two **heap;
int cap, count;
} PriorityQueue;
void swap(Two *a, Two *b)
{
Two store = *a;
*a = *b;
*b = store;
return;
}
int greater(Two *a, Two *b)
{
return (a->v > b->v);
}
PriorityQueue InitPriorityQueue(int n)
{
PriorityQueue q;
q.heap = (Two**)malloc(n * sizeof(Two*));
q.cap = n;
q.count = 0;
return q;
}
void Insert(PriorityQueue *q, Two *ptr)
{
int i = q->count;
q->count = i + 1;
q->heap[i] = ptr;
while ((i > 0) && greater(q->heap[(i - 1) / 2], q->heap[i]))
{
swap(q->heap[(i - 1) / 2], q->heap[i]);
q->heap[i]->index = i;
i = (i - 1) / 2;
}
q->heap[i]->index = i;
return;
}
void Heapify(int i, int n, Two **heap)
{
int left, right, j;
while (1)
{
left = 2 * i + 1;
right = left + 1;
j = i;
if ((left < n) && greater(heap[i], heap[left]))
{
i = left;
}
if ((right < n) && (greater(heap[i], heap[right])))
{
i = right;
}
if (i == j)
{
break;
}
swap(heap[i], heap[j]);
heap[i]->index = i;
heap[j]->index = j;
}
}
Two *ExtractMin(PriorityQueue *q)
{
Two *ptr = q->heap[0];
q->count = q->count - 1;
if (q->count > 0)
{
q->heap[0] = q->heap[q->count];
q->heap[0]->index = 0;
Heapify(0, q->count, q->heap);
}
return ptr;
}
int main(int argc, char** argv)
{
int n, m, i, start, end, ttk;
Two *firstout;
end = 0;
scanf("%d %d", &n, &m);
PriorityQueue pq = InitPriorityQueue(n);
for(i = 0; i < m; i++)
{
scanf("%d %d", &start, &ttk);
Two *ptr = (Two*)malloc(sizeof(Two));
ptr->index = pq.count;
if (pq.count == n)
{
firstout = ExtractMin(&pq);
start = start > firstout->v ? start : firstout->v;
free(firstout);
}
ptr->v = start + ttk;
end = end < ptr->v ? ptr->v : end;
Insert(&pq, ptr);
}
for (i = pq.count; i > 0; i--)
{
firstout = ExtractMin(&pq);
end = end < firstout->v ? firstout->v : end;
free(firstout);
}
printf("%d", end);
free(pq.heap);
return 0;
}