标签:hdu3722
题意:告诉纸牌之间的边的权重时第一个字符串逆序,和第二个字符串的最长公共前缀,预处理下这个权重。在KM下即可
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc) freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
using namespace std;
const int maxn=205;
const int inf=1<<28;
int w[maxn][maxn];
int linker[maxn],lx[maxn],ly[maxn],slack[maxn];
bool visx[maxn],visy[maxn];
int nx,ny;
bool dfs(int x){
visx[x]=true;
for(int i=0;i<ny;i++){
if(visy[i])continue;
int tmp=lx[x]+ly[i]-w[x][i];
if(tmp==0){
visy[i]=true;
if(linker[i]==-1||dfs(linker[i])){
linker[i]=x;
return true;
}
}else if(slack[i]>tmp){
slack[i]=tmp;
}
}
return false;
}
int km(){
cl(linker,-1);
cl(ly,0);
for(int i=0;i<nx;i++){
lx[i]=-inf;
for(int j=0;j<ny;j++)if(w[i][j]>lx[i]){lx[i]=w[i][j];}
}
for(int x=0;x<nx;x++){
fill(slack,slack+ny+1,inf);
while(true){
cl(visx,false);
cl(visy,false);
if(dfs(x))break;
int d=inf;
for(int i=0;i<ny;i++)if(!visy[i]&&slack[i]<d){
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 ans=0;
bool ok=false;
for(int i=0;i<ny;i++)if(linker[i]!=-1){
ans+=w[linker[i]][i];
if(w[linker[i]][i]==-inf)ok=true;///
}
if(ok)return 1;
return ans;
}
char a[maxn][1005];
int getprefix(char *s,char *t){
int n=strlen(s);
int m=strlen(t);
int i=n-1,j=0;
int cnt=0;
while(i>=0&&j<m){
if(s[i]==t[j])cnt++;
else break;
i--;j++;
}
return cnt;
}
int main(){
int n;
while(~scanf("%d",&n)){
for(int i=0;i<n;i++){
scanf("%s",&a[i]);
}
nx=ny=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j)w[nx][j]=0;
else {
w[nx][j]=getprefix(a[i],a[j]);
}
}
nx++;
}
ny=n;
//printf("nx = %d, ny = %d\n",nx,ny);
printf("%d\n",km());
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:hdu3722
原文地址:http://blog.csdn.net/u013167299/article/details/48139269