题目链接:点我~~
题意:给n个字符串,然后对于任意两个字符串进行匹配,第一个翻转后与第二个匹配,最长公共前缀为得分,自己到自己为0。
思路:将字符串预处理建图,然后跑KM。
#include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> PI; typedef pair< PI, int> PII; const double eps=1e-5; const double pi=acos(-1.0); const int mod=1e9+7; const int INF=0x3f3f3f3f; #define Key_value ch[ch[root][1]][0] const int MAXN = 800000; const int MAXM = 1250; int nx,ny; int g[MAXM][MAXM]; int linker[MAXM],lx[MAXM],ly[MAXM]; int slack[MAXM]; bool visx[MAXM],visy[MAXM]; bool DFS(int x) { visx[x] = true; for(int y = 0; y < ny; y++) { if(visy[y])continue; int tmp = lx[x] + ly[y] - g[x][y]; if(tmp == 0) { visy[y] = true; if(linker[y] == -1 || DFS(linker[y])) { linker[y] = x; return true; } } else if(slack[y] > tmp) slack[y] = tmp; } return false; } int KM() { memset(linker,-1,sizeof(linker)); memset(ly,0,sizeof(ly)); for(int i = 0; i < nx; i++) { lx[i] = -INF; for(int j = 0; j < ny; j++) if(g[i][j] > lx[i]) lx[i] = g[i][j]; } for(int x = 0; x < nx; x++) { for(int i = 0; i < ny; i++) slack[i] = INF; while(true) { memset(visx,false,sizeof(visx)); memset(visy,false,sizeof(visy)); if(DFS(x))break; int d = INF; for(int i = 0; i < ny; i++) if(!visy[i] && d > slack[i]) d = slack[i]; for(int i = 0; i < nx; i++) if(visx[i]) lx[i] -= d; for(int i = 0; i < ny; i++) { if(visy[i])ly[i] += d; else slack[i] -= d; } } } int res = 0; for(int i = 0; i < ny; i++) if(linker[i] != -1) res += g[linker[i]][i]; return res; } //HDU 2255 int main() { int n; string str[205]; while(~scanf("%d",&n)) { for(int i = 0; i < n; i++) cin>>str[i]; for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) g[i][j]=0; for(int i=0; i<n; ++i) { int len=str[i].size(); string tmp=str[i]; reverse(tmp.begin(),tmp.end()); for(int j=0; j<n; ++j) { if(i==j) continue; int t=min(len,(int)str[j].size()); int cnt=0; for(int k=0; k<t; ++k) { if(tmp[k]==str[j][k]) { cnt++; } else break; } g[i][j]=cnt; } } nx = ny = n; printf("%d\n",KM()); } return 0; }
- 版权声明:本文基于《知识共享署名-相同方式共享 3.0 中国大陆许可协议》发布,转载请遵循本协议
- 文章链接:http://www.carlstedt.cn/archives/1199 (转载时请注明本文出处及文章链接)
发表评论
快来吐槽一下吧!