生活随笔
收集整理的這篇文章主要介紹了
【Uva 1625】Color Length
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【Link】:
【Description】
給你兩個序列,都由大寫字母組成;
每次,把兩個序列中的一個的開頭字母加在字符串的尾端,然后在那個序列中刪掉那個開頭字母;
最后得到一個字符串;
這個字符串顯然后很多種;
讓你找所有字母的L(C)的和的最小值;
L(c)是某個字母在最后的那個字符串中出現的結尾位置和開始位置的差值;
【Solution】
設f[i][j]表示第一個序列1..i全都移除掉了,第二個序列1..j全都移除掉了的最小L(c)和;
這里不能直接算出某個字母的L(C)值,但是能一步一步地累加,比如,你新加了一個字母x,然后在此之前,已有的字符串里面,有字母a,且還有未加入的字母a;
則L(a)的值可以肯定會遞增1了;
則可以寫出轉移方程
f[i][j]=min(f[i][j],f[i?1][j]+cnt[i?1][j])
f[i][j]=min(f[i][j],f[i][j?1]+cnt[i][j?1]);
這里的cnt[i][j]表示第一個序列前i個字母移出去了,第二個序列前j個字母移出去了所形成的字符串,有多少個字母已經出現了,但是還沒有全部出現;
為了獲取這個cnt數組;
可以先獲取,每個字母在這兩個序列中第一次出現和最后一次出現的位置;
然后對于枚舉的i和j;
看看每個字母是不是在這個情況下出現了;
這樣就能獲得cnt數組;
【NumberOf WA】
4
【Reviw】
用memset會莫名的TLE;
改成循環就過了
【Code】
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define Open() freopen("F:\\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0)typedef pair<
int,
int> pii;
typedef pair<LL,LL> pll;
const int dx[
9] = {
0,
1,-
1,
0,
0,-
1,-
1,
1,
1};
const int dy[
9] = {
0,
0,
0,-
1,
1,-
1,
1,-
1,
1};
const double pi =
acos(-
1.0);
const int N =
5e3;
const int INF =
0x3f3f3f3f;
int dp[N+
100][N+
100],n,m,cnt[N+
100][N+
100];
pii a1[
27],a2[
27];
char s1[N+
100],s2[N+
100];
int main(){
int T;
scanf(
"%d",&T);
while (T--){
scanf(
"%s",s1+
1);
scanf(
"%s",s2+
1);n =
strlen(s1+
1),m =
strlen(s2+
1);rep1(i,
1,
26) a1[i].fi = a1[i].se = a2[i].fi = a2[i].se =
0;rep1(i,
1,n){
int t = s1[i]-
'A'+
1;
if (a1[t].fi==
0) a1[t].fi = i;}rep1(i,
1,m){
int t = s2[i]-
'A'+
1;
if (a2[t].fi==
0) a2[t].fi = i;}rep2(i,n,
1){
int t = s1[i]-
'A'+
1;
if (a1[t].se==
0) a1[t].se = i;}rep2(i,m,
1){
int t = s2[i]-
'A'+
1;
if (a2[t].se==
0) a2[t].se = i;}rep1(i,
0,n)rep1(j,
0,m){
int temp =
26;rep1(k,
1,
26){
if (a1[k].fi ==
0 && a2[k].fi==
0){temp--;
continue;}
if (a1[k].fi!=
0 && a2[k].se==
0){
if (i<a1[k].fi){temp--;
continue;}
if (a1[k].se<=i){temp--;
continue;}}
if (a1[k].fi==
0 && a2[k].se!=
0){
if (j<a2[k].fi){temp--;
continue;}
if (a2[k].se<=j){temp--;
continue;}}
if (a1[k].fi!=
0 && a2[k].fi!=
0){
if (i<a1[k].fi && j<a2[k].fi){temp--;
continue;}
if (a1[k].se<=i && a2[k].se<=j){temp--;
continue;}}}cnt[i][j] = temp;}rep1(i,
0,n)rep1(j,
0,m)dp[i][j] = INF;dp[
0][
0] =
0;rep1(i,
0,n)rep1(j,
0,m){
if (i-
1 >=
0){dp[i][j] = min(dp[i][j],dp[i-
1][j] + cnt[i-
1][j]);}
if (j-
1 >=
0){dp[i][j] = min(dp[i][j],dp[i][j-
1] + cnt[i][j-
1]);}}
cout << dp[n][m] << endl;}
return 0;
}
轉載于:https://www.cnblogs.com/AWCXV/p/7626202.html
總結
以上是生活随笔為你收集整理的【Uva 1625】Color Length的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。