Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3263 | Accepted: 1172 |
Description
Input
Output
Sample Input
5 abc bcd cde aaa bfcde 0
Sample Output
8
Hint
aaa abc bcd cde bfcde
Source
#include <map> #include <set> #include <list> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int dp[1100][15]; int match[15][15]; char str[15][15]; int max_match(char a[], char b[]) { int cnt = 0; int x = 0; while (a[x] != '\0') { int s = x; int t = 0; int ans = 0; while (a[s] != '\0' && b[t] != '\0') { if (a[s] == b[t]) { ans++; } s++; t++; } cnt = max(ans, cnt); x++; } return cnt; } int main() { int n; while (~scanf("%d", &n), n > 0) { memset (dp, 0, sizeof(dp)); for (int i = 0; i < n; ++i) { scanf("%s", str[i]); } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { match[i][j] = max_match(str[i], str[j]); match[j][i] = max_match(str[j], str[i]); match[i][j] = match[j][i] = max(match[i][j], match[j][i]); } } for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < n; ++j) { if (i & (1 << j))//第j位是0 { continue; } for (int k = 0; k < n; ++k) { if (j == k) { continue; } if (!(i & (1 << k))) { continue; } dp[i ^ (1 << j)][j] = max(dp[i ^ (1 << j)][j], dp[i][k] + match[k][j]); } } } int ans = 0; for (int i = 0; i < n; ++i) { ans = max(ans, dp[(1 << n) - 1][i]); // printf("%d\n", dp[(1 << n) - 1][i]); } printf("%d\n", ans); } return 0; }