Skip to content

Instantly share code, notes, and snippets.

@soulmachine
Created August 10, 2013 08:32
Show Gist options
  • Save soulmachine/6199601 to your computer and use it in GitHub Desktop.
Save soulmachine/6199601 to your computer and use it in GitHub Desktop.
WIKIOI 2298 石子合并, http://www.wikioi.com/problem/2298/ POJ 1738 An old Stone Game, http://poj.org/problem?id=1738 Garsia-Wachs算法
#include <stdio.h>
#define MAXN 55555
int N, A[MAXN]; /* 堆数,每堆的石头个数 */
int num, result; /* 数组实际长度,结果 */
void combine(int k) { /* 前提 A[k-1] < A[k+1] */
int i, j;
/* 合并 k-1和k */
int temp=A[k] + A[k-1];
result += temp;
/* 紧缩 */
for(i = k; i < num - 1; i++) A[i] = A[i+1];
num--;
/* 插入temp到合适位置 */
for(j = k-1; j > 0 && A[j-1] < temp; j--) A[j] = A[j-1];
A[j] = temp;
/* why? */
while(j >= 2 && A[j] >= A[j-2]) {
int d = num - j;
combine(j - 1);
j = num - d;
}
}
int main() {
int i;
scanf("%d",&N);
if(N == 0) return 0;
for(i = 0; i < N; i++) scanf("%d", &A[i]);
num=2;
result=0;
for(i = 2; i < N; i++) {
A[num++] = A[i];
while(num >= 3 && A[num-3] <= A[num-1]) combine(num-2);
}
while(num > 1) combine(num-1);
printf("%d\n",result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment