4 10 20 30 04 5 2 3 4 3 4
1 2
搜索的Trie 的题目,可是还是不会啊=。=
看完题的思路是求有多少个最长上升子序列,始终超时。
discuss说求相等的最大个数,所以map就可以很轻松的AC了。
超时代码:
#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<algorithm> #include<string> #include<queue> using namespace std; #pragma warning(disable : 4996) const int MAX = 3005; int dp[MAX], num[MAX]; bool visited[MAX]; int ans; void LIS(int *arr, int n) { int len = -1; for (int i = 1; i <= n; i++) { dp[i] = 0; } for(int i = 1; i <= n; i++) { dp[i] = 1; for(int j = 1; j < i; j++) { if(arr[i] > arr[j] && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1; } if(dp[i] > len) { len = dp[i]; } } for (int i = 1; i <= n; i++) { visited[i] = false; } int x = 1; for (int i = 1; i <= n; i++) { if(dp[i] == x) { visited[i] = true; x++; } if(x == len + 1) { break; } } int index = 1; for (int i = 1; i <= n; i++) { if(!visited[i]) { num[index++] = arr[i]; } } if (index == 1) { return; } else { ans++; LIS(num, index - 1); } } int main() { //freopen("in.txt", "r", stdin); int n; int array[MAX] ={0}; while (scanf("%d", &n) != EOF) { for (int i = 1; i <= n; i++) { scanf("%d", &array[i]); } sort(array + 1, array + n + 1); ans = 1; LIS(array, n); printf("%d\n", ans); } return 0; }map:
#include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include<map> #include <cstdio> using namespace std; int main() { int n,i,j,maxnum; while(scanf("%d",&n)==1) { maxnum=-1; map<int,int>Map; for(i=0;i<n;i++) { scanf("%d",&j); Map[j]++; if(Map[j]>maxnum) maxnum=Map[j]; } printf("%d\n",maxnum); } return 0; }
Trie
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<cmath> #include<vector> #include<algorithm> #include<set> #include<string> #include<queue> #include <stack> using namespace std; #pragma warning(disable : 4996) #define MAX 10 typedef struct Node { struct Node *next[MAX]; int v; }Node, *Trie; Trie root; int ans; void init() { root = (Trie)malloc(sizeof(Node)); root->v = 0; for (int i = 0; i < MAX; i++) { root->next[i] = NULL; } ans = 0; } void createTrie(char *str) { int len, i, j; Node *current, *newnode; len = strlen(str); if(len == 0) { return; } current = root; j = 0; while (str[j] == '0' && j < len - 1) { j++; } for(i = j; i < len; i++) { int id = str[i] - '0'; if(current->next[id] == NULL) { newnode = (Node *)malloc(sizeof(Node)); newnode->v = 0; for(j = 0; j < MAX; j++) { newnode->next[j] = NULL; } current->next[id] = newnode; current = current->next[id]; } else { current = current->next[id]; } } current->v++; if(current->v > ans) { ans = current->v; } } void dealTrie(Trie T) { for(int i = 0; i < MAX; i++) { if(T->next[i] != NULL) { dealTrie(T->next[i]); } } free(T); } int main() { freopen("in.txt", "r", stdin); int n; char str[35] = {0}; while (scanf("%d", &n) != EOF) { init(); while (n--) { scanf("%s", str); createTrie(str); } printf("%d\n", ans); dealTrie(root); } return 0; }