题意:给出了n个箱子,和d个相关参数,如果两个箱子其中任何一个参数都比另一个小则可以嵌套到另一个箱子里,要求输出箱子最多能嵌套层数和嵌套的编号顺序。
题解:先建立有向无环图,如果box[i]的任意一个参数小于box[j],则g[i][j] = 1,图建好以后,f(i)表示从结点i的最长路长度,f(i) = max{(f(j) + 1)| (i, j) 属于e},e代表连通的边集,记忆式搜寻最优解(f[i]初始化为0),然后输出f[i]中最大的值,并从最大值编号开始递归找到路径编号。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 35;
int box[N][N], n, d, g[N][N], f[N], res[N], num;
int dp(int i) {
if (f[i] > 0)
return f[i];
f[i] = 1;
for (int j = 0; j < n; j++)
if (g[i][j]) {
int temp = dp(j) + 1;
f[i] = f[i] > temp ? f[i] : temp;
}
return f[i];
}
void printf_ans(int i) {
res[num++] = i + 1;
for (int j = 0; j < n; j++)
if (g[i][j] && f[i] == f[j] + 1) {
printf_ans(j);
break;
}
}
int main() {
while (scanf("%d%d", &n, &d) != EOF) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++)
scanf("%d", &box[i][j]);
sort(box[i], box[i] + d);
}
memset(g, 0, sizeof(g));
memset(f, 0, sizeof(f));
num = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp1 = 0, temp2 = 0;
for (int k = 0; k < d; k++)
if (box[i][k] < box[j][k])
temp1++;
else if (box[i][k] > box[j][k])
temp2++;
if (temp1 == d)
g[i][j] = 1;
else if (temp2 == d)
g[j][i] = 1;
}
}
for (int i = 0; i < n; i++)
dp(i);
int length = 0, k;
for (int i = 0; i < n; i++)
if (f[i] > length) {
length = f[i];
k = i;
}
printf("%d\n", length);
printf_ans(k);
printf("%d", res[0]);
for (int i = 1; i < num; i++)
printf(" %d", res[i]);
printf("\n");
}
return 0;
}