# 指標_最後的元素

user_3763047219
c_cpp
2 years ago
1.4 kB
1
Indexable
Never
```int extractMax(int* stone, int stoneSize);
int insert(int* stone, int stoneSize);
int lastStoneWeight(int* stones, int stonesSize);

int extractMax(int* stone, int stoneSize) {
int max = 0;
int index = 0;
for (int i = 0; i < stoneSize; i++) {
if (max < stone[i]) {
max = stone[i];
index = i;
}
}

return index;
}

int insert(int* stone, int stoneSize) {
int x = 0, y = 0;
int ix = 0, iy = 0;
while (y>=0) {
iy = extractMax(stone, stoneSize);
if (stone[iy] != -1) {
y = stone[iy];
stone[iy] = -1;
ix = extractMax(stone, stoneSize);
if (stone[ix] == -1) {
return y;
}
else {
x = stone[ix];
stone[ix] = -1;
if (x != y) {
stone[iy] = y - x;
}
}
}
else {
return 0;
}
}

}

int lastStoneWeight(int* stones, int stonesSize) {
return insert(stones, stonesSize);
}

#include <stdio.h>
#include <stdlib.h>

int main() {
int n = 0;
int ans;
scanf("%d", &n);
int* a = (int*)malloc(n * sizeof(int));

for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
ans = lastStoneWeight(a, n);
printf("%d", ans);
free(a);
return 0;
}```