sdut2536字母哥站队(dp)
简单DP 说是简单 还是推了好一会 推出来觉得好简单
保留当前i的最小值 dp[i] = min(dp[i],dp[j]+i-j-1) j<i
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 #define INF 0xfffffff 8 char s[5010]; 9 int w[500][500],dp[5010]; 10 int main() 11 { 12 int i,j,k,n; 13 char a,b; 14 while(cin>>s) 15 { 16 memset(dp,0,sizeof(dp)); 17 memset(w,0,sizeof(w)); 18 cin>>n; 19 k = strlen(s); 20 for(i = 1 ; i <= n ; i++) 21 { 22 cin>>a>>b; 23 w[a][b] = 1; 24 w[b][a] = 1; 25 } 26 dp[0] = 0; 27 for(i = 1 ; i < k ; i++) 28 { 29 dp[i] = i; 30 for(j = i-1 ; j >= 0 ; j--) 31 if(!w[s[i]][s[j]]) 32 dp[i] = min(dp[i],dp[j]+i-j-1); 33 } 34 int ans = INF; 35 for(i =0 ; i < k ; i++) 36 ans = min(ans,dp[i]+k-i-1); 37 cout<<ans<<endl; 38 } 39 return 0; 40 }