Uvs -- 111 History Grading + dp
Question:
In fact, it is to find the longest common subsequence of the two sequences.
Ideas:
The input of this question is very difficult. If you understand the input clearly, it will be difficult. The input of a question indicates the position where the number is stored. For example, if the input is 1, 3, and 2, the corresponding sequence of 2 and 4 should be 1, 3, 2, and 4;
The following two pieces of code are provided: one is a classic solution, and the other is the code that I wrote today to convert the problem into the longest path for solving the DAG graph.
The Code is as follows:
#include
#include
#include
using namespace std;int d[30],n,map[30][30];int dp(int i){ if(d[i]>0) return d[i]; d[i]=1; for(int j=1;j<=n;j++) if(map[i][j]) { int t=dp(j)+1; if(d[i]
#include
#include
#include
using namespace std;int main(){ int i,j,a[30],b[30],dp[30][30],n; while(scanf("%d",&n)!=EOF) { int x; for(i=1;i<=n;i++) { scanf("%d",&x); a[x]=i; } while(scanf("%d",&x)!=EOF) { b[x]=1; for(i=2;i<=n;i++) { scanf("%d",&x); b[x]=i; } memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(a[i]==b[j]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } int ans=0; for(i=1;i<=n;i++) for(j=1;j<=n;j++) ans=max(ans,dp[i][j]); printf("%d\n",ans); } } return 0;}