题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=47
LCS类型的题目。
题目中有一点真的读题的时候需要注意:Given the correct chronological order of n events 1; 2; : : : ; n as c1; c2; : : : cn where 1 <= ci <= n denotes the ranking of event i in the correct chronological order .所以 2 3 1 4 指的是event 1 应该被排在第2位,event 2 应该被排在第3位.......
代码如下:
1 #include <iostream> 2 #include <math.h> 3 #include <stdio.h> 4 #include <cstdio> 5 #include <algorithm> 6 #include <string.h> 7 #include <string> 8 #include <sstream> 9 #include <cstring> 10 #include <queue> 11 #include <vector> 12 #include <functional> 13 #include <cmath> 14 #define SCF(a) scanf("%d", &a) 15 #define IN(a) cin>>a 16 #define FOR(i, a, b) for(int i=a;i<b;i++) 17 typedef long long Int; 18 using namespace std; 19 20 int main() 21 { 22 int n = 0; 23 int correct[25]; 24 int current[25]; 25 int dp[25][25]; 26 string in; 27 int state = 2; 28 int cnum; 29 while (getline(cin, in)) 30 { 31 stringstream iss; 32 iss << in; 33 if (state == 1) 34 { 35 FOR(i, 0, n) 36 { 37 iss >> cnum; 38 correct[cnum-1] = i+1; 39 } 40 state = 2; 41 } 42 else if (state == 2) 43 { 44 int num = 0; 45 while (iss >> cnum) 46 { 47 current[cnum - 1] = num + 1; 48 num++; 49 } 50 if (num > 1) 51 { 52 FOR(i, 0, n) 53 { 54 dp[0][i] = dp[i][0] = 0; 55 } 56 FOR(i, 1, n + 1) 57 { 58 FOR(j, 1, n + 1) 59 { 60 if (correct[i - 1] == current[j - 1]) 61 dp[i][j] = dp[i - 1][j - 1] + 1; 62 else 63 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 64 } 65 } 66 printf("%d\n", dp[n][n]); 67 } 68 else 69 { 70 state = 1; 71 n = cnum; 72 } 73 } 74 } 75 return 0; 76 }