1、UVA103 嵌套n维空间 DAG模型记忆化搜索,或者 最长上升子序列。
2、dp[i]=max( dp[j]+1),(第i个小于第j个)
(1)
//DAG模型记忆化搜索 #include<bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:102400000,102400000") #define F(i,a,b) for (int i=a;i<b;i++) #define FF(i,a,b) for (int i=a;i<=b;i++) #define mes(a,b) memset(a,b,sizeof(a)) #define INF 0x3f3f3f3f typedef long long ll; const int N = 1e6+10, M=35; int n,m; int box[M][M],dp[M],fa[M],vis[M],G[M][M]; bool jBigi(int a,int b) { FF(i,1,m) if(box[a][i]>=box[b][i]) return false; return true; } int D(int x) { if(vis[x]) return dp[x]; vis[x]=1; int &ans=dp[x]=1; FF(i,1,n) if(G[x][i] && ans<D(i)+1) { ans=D(i)+1, fa[x]=i; } return ans; } void print_ans(int mi) { printf("%d ", dp[mi]); int first=1; while(mi!=-1) { if(!first) printf(" "); first=0; printf("%d", mi); mi=fa[mi]; } printf(" "); } int main() { while(~scanf("%d%d", &n,&m)) { FF(i,1,n) { FF(j,1,m) scanf("%d", &box[i][j]); sort(box[i]+1,box[i]+1+m); } mes(G,0); mes(vis,0); mes(fa,-1); FF(i,1,n) FF(j,1,n) if(jBigi(i,j)) G[i][j]=1; int maxn=-INF, mi; FF(i,1,n) { dp[i]=D(i); if(maxn<dp[i]) maxn=dp[i], mi=i; } print_ans(mi); } return 0; }
(2)
//最长上升子序列 #include<bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:102400000,102400000") #define F(i,a,b) for (int i=a;i<b;i++) #define FF(i,a,b) for (int i=a;i<=b;i++) #define mes(a,b) memset(a,b,sizeof(a)) #define INF 0x3f3f3f3f typedef long long ll; const long long LINF = 1e18+1LL; const int N = 1e5+10, M = 35; int dp[M],fa[M],n,m; struct box { int di[M],ord; void Sort() { sort(di+1,di+m+1); } friend bool operator < (const box & a, const box & b) { FF(i,1,m) if(a.di[i]>b.di[i]) return false; //注:这里不能>=,必须>。因为是重载<,要尽可能使a<b return true; } }B[M]; bool jBigi(int a,int b) { FF(i,1,m) if(B[a].di[i]>=B[b].di[i]) return false; return true; } void print_ans(int mi) { printf("%d ", dp[mi]); int first=1; while(mi!=-1) { if(!first) printf(" "); first=0; printf("%d", B[mi].ord); mi=fa[mi]; } printf(" "); } int main() { while(~scanf("%d%d", &n,&m)) { FF(i,1,n) { FF(j,1,m) scanf("%d", &B[i].di[j]); B[i].Sort(); B[i].ord=i; } sort(B+1,B+1+n); mes(fa,-1); int maxn=-INF, mi; for(int i=n; i>0; --i) { dp[i]=1; for(int j=n; j>i; --j) { if(jBigi(i,j) && dp[i]<dp[j]+1) { dp[i]=dp[j]+1, fa[i]=j; } if(maxn<dp[i]) maxn=dp[i], mi=i; } } print_ans(mi); } return 0; }