UVA 103 Stacking Boxes

記憶化搜索

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <memory.h>
using namespace std;
struct Box {
	int index;
	vector<int> dimensions;
}; 
// 判斷b2是否可以包含b1 
bool cmp(const Box& b1, const Box& b2) {
	int i;
	for (i=0;i<b1.dimensions.size();i++) {
		if (b2.dimensions[i]<=b1.dimensions[i])
			return false;
	}
	return true;
}
Box boxes[40];
int dp[40];
int k,n;
int parent[40];
vector<int> path;
int DFS_DP(int x) {
	if (dp[x]!=0)
		return dp[x];
	dp[x]=1;
	int i;
	for (i=0;i<k;i++) {
		if (cmp(boxes[i], boxes[x])==true) {
			int tmp = DFS_DP(i);
			if (tmp+1>dp[x]) {
				dp[x]=tmp+1;
				parent[x]=i;
			}
		}
	}
	return dp[x];
}
int main() {
	int i, j;
	Box tmp;
	int num;
	
	while (scanf("%d",&k)!=EOF) {
		scanf("%d",&n);
		for (i=0;i<40;i++) {
			boxes[i].dimensions.clear();
			parent[i]=-1;
		}
		for (i=0;i<k;i++) {
			tmp.index = i+1;
			for (j=0;j<n;j++) {
				scanf("%d",&num);
				tmp.dimensions.push_back(num);	
			}
			sort(tmp.dimensions.begin(), tmp.dimensions.end());
			boxes[i]=tmp;
			tmp.dimensions.clear();
		}
		memset(dp,0,sizeof(dp));
		num=1;
		int index=0;
		for (i=0;i<k;i++) {
			j=DFS_DP(i);
			if (j>num) {
				num=j;
				index=i;
			}
		}
		path.clear();
		while (parent[index]!=-1) {
			path.push_back(index);
			index=parent[index];
		}
		path.push_back(index);
		printf("%d\n", num);
		for (i=path.size()-1;i>0;i--)
			printf("%d ", path[i]+1);
		printf("%d\n", path[i]+1);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章