题目:uva103 - Stacking Boxes(DAG)
题目大意:给出N个boxes, 而且给出这些箱子的维度。要求找一个最长的序列。可以使得以下的箱子一定可以有个维度序列大于上面的那个箱子的维度序列。比如:A箱子(2 3 4),B箱子(3 4 5),由于有个序列2 3 4 。 3 4 5使得B每一个维度的值都大于A,所以A可以在B上面 。
解题思路:DAG。将这些箱子哪个能在哪个上面处理出有向图出来,这里推断能否够在上面的情况,仅仅要将这两个箱子的维度都从小到大排下序,然后比較一下是否相应的位置的值要不都比还有一个小就能够了。
比如 :
31 4 18 8 27 17
44 32 13 19 41 19
排序
4 8 17 18 27 31
13 19 19 32 41 44
发现上面的数字比以下的相应位置的数字小。就能够。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 35;
const int M = 15;
int n, m;
int box[N][M];
int G[N][N];
int f[N][N];
int path[N][N];
bool judge (int a, int b) {
for (int i = 0; i < m; i++)
if (box[a][i] >= box[b][i])
return false;
return true;
}
void handle () {
memset (G, 0, sizeof (G));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (i == j)
continue;
if (judge(i, j))
G[i][j] = 1;
}
}
void init () {
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
f[i][j] = -1;
}
int dp (int x, int y) {
int& ans = f[x][y];
int temp;
if (ans != -1)
return ans;
for (int i = 0; i < n; i++)
if (G[y][i]) {
temp = dp(y, i) + 1;
if (temp > ans) {
ans = temp;
path[x][y] = i;
}
}
if (ans == -1) {
ans = 2;
path[x][y] = -1;
}
return ans;
}
void printf_ans(int x, int y) {
if (path[x][y] == -1)
return;
printf (" %d", path[x][y] + 1);
printf_ans(y, path[x][y]);
}
int main () {
while (scanf ("%d%d", &n, &m) != EOF) {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf ("%d", &box[i][j]);
for (int i = 0; i < n; i++)
sort (box[i], box[i] + m);
handle ();
init();
int ans = 1;
int temp;
int x, y;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (G[i][j]) {
temp = dp(i, j);
if (temp > ans) {
ans = temp;
x = i;
y = j;
}
}
printf ("%d\n", ans);
if (ans != 1) {
printf("%d %d", x + 1, y + 1);
printf_ans(x, y);
} else
printf ("1");
printf ("\n");
}
return 0;
}