DP找次最大最大子序列
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <ctime> 5 #include <cmath> 6 #include <cctype> 7 #include <string> 8 #include <vector> 9 #include <map> 10 #include <set> 11 #include <stack> 12 #include <algorithm> 13 #include <iostream> 14 using namespace std; 15 typedef long long ll; 16 const int NO = 1000 + 10; 17 vector <int> vis[NO]; 18 int num[NO]; 19 int dp[NO]; 20 int n; 21 22 inline bool dfs( int x ) 23 { 24 if( vis[x].size() > 1 ) 25 return true; 26 for( int i = 0; i < vis[x].size(); ++i ) 27 { 28 bool flag = dfs( vis[x][i] ); 29 if( flag ) 30 return true; 31 } 32 return false; 33 } 34 35 int main() 36 { 37 int T; 38 scanf( "%d", &T ); 39 while( T-- ) 40 { 41 scanf( "%d", &n ); 42 for( int i = 0; i < n; ++i ) 43 scanf( "%d", &num[i] ); 44 int ans = 0, cur, Max = 0; 45 for( int i = 0; i < n; ++i ) 46 { 47 vis[i].clear(); 48 dp[i] = 1; 49 for( int j = 0; j < i; ++j ) 50 if( num[i] > num[j] ) 51 { 52 if( dp[i] < dp[j] + 1 ) 53 { 54 vis[i].clear(); 55 dp[i] = dp[j] + 1; 56 vis[i].push_back( j ); 57 } 58 else if( dp[i] == dp[j] + 1 ) 59 vis[i].push_back( j ); 60 } 61 if( Max < dp[i] ) 62 { 63 cur = i; 64 ans = 1; 65 Max = dp[i]; 66 } 67 else if( Max == dp[i] ) 68 { 69 ++ans; 70 cur = i; 71 } 72 } 73 if( ans > 1 ) 74 { 75 printf( "%d ", Max ); 76 continue; 77 } 78 if( dfs( cur ) ) 79 printf( "%d ", Max ); 80 else 81 printf( "%d ", Max-1 ); 82 } 83 return 0; 84 }