UVA 437 - The Tower of Babylon

是一道归根于最长上升子序列的问题,权值1改为高度h,因为要求最大上升子序列,要先排序,这里按面积升序排序,使后面的面积大的block不会叠在前面面积小的block之上,便于递推,这里用qsort排序方便很多。

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n, x[95], y[95], h[95], f[95], r[95];
int cmp(const void *_p, const void *_q)
{
int *p = (int *)_p;
int *q = (int *)_q;
return (x[*p] * y[*p]) - (x[*q] * y[*q]);
}
void solve()
{
memset(f,0,sizeof(f));
for(int i = 1; i <= 3*n; i ++)
for(int j = i; j <= 3*n; j ++)
if((x[r[i]]<x[r[j]]&&y[r[i]]<y[r[j]])||(x[r[i]]<y[r[j]]&&y[r[i]]<x[r[j]]))
{
if(f[j] < f[i] + h[r[i]])
f[j] = f[i] + h[r[i]];
}
int max = 0;
for(int i = 1; i <= 3*n; i ++)
if(f[i]+h[r[i]] > max) max = f[i] + h[r[i]];
printf("%d\n",max);
}
void input()
{
int num = 0;
while(scanf("%d",&n) == 1)
{
if(n == 0) break;
for(int i = 1,j = 1; i <= n; i ++, j += 3)
{
scanf("%d%d%d",&x[j], &y[j], &h[j]);
h[j+1] = x[j];
x[j+1] = h[j];
y[j+1] = y[j];
h[j+2] = y[j];
x[j+2] = x[j];
y[j+2] = h[j];
}
num ++;
for(int i = 0; i <= 3*n; i ++)
r[i] = i;
qsort(r+1,3*n,sizeof(r[1]),cmp);
printf("Case %d: maximum height = ",num);
solve();
}
}
int main()
{
input();
return 0;
}



你可能感兴趣的:(uva)