题目地址 :
题意:一个字符串,交换最少的次数,使得不存在VK
题解:DP
官方题解很牛B。
Letters different than 'V' and 'K' are indistinguishable, so we can treat all of them as the same letter 'X'.
We will try to build the final string from left to right Let dp[v][k][x] denote the number of moves needed to move first v letters 'V', first kletters 'K' and first x letters 'X' to the beginning of the string (those letters should become first v + k + x letters of the string). We should also remember the last used letter (to ensure that there is no 'K' just after 'V') so let's extend the state to dp[v][k][x][lastLetter] (or it can be dp[v][k][x][is_the_last_letter_V]).
To move from a state, we should consider taking the next 'K' (i.e. the k + 1-th letter 'K' in the initial string), the next 'V' or the next 'X'. Of course, we can't take 'K' if the last used letter was 'V'.
The last step is to see how we should add to the score when we add a new letter. It turns out that it isn't enough to just add the difference between indices (where the letter was and where it will be) and the third sample test ("VVKEVKK") showed that. Instead, we should notice that we know which letters are already moved to the beginning (first k letters 'K' and so on) so we know how exactly the string looks like currently.
For example, let's consider the string "VVKXXVKVV" and moving from the state v = 4, k = 1, x = 1 by taking a new letter 'K'. We know that first 4 letters 'V', 1 letter 'K' and 1 letter 'X' are already moved to the beginning. To move the next letter 'K' (underlined in blue on the drawing below) to the left, we must swap it with all not-used letters that were initially on the left from this 'K'. Counting them in linear time gives the total complexity O(n4) but you can also think a bit and get O(n3) - it's quite easy but it wasn't required to get AC. On the drawing below, used letters are crossed out. There is only 1 not-crossed-out letter on the left from 'K' so we should increase the score by 1 (because we need 1 swap to move this 'K' to the x + k + v + 1-th position).
地址:
1 #include2 #include 3 const int inf = 0x3f3f3f3f; 4 using namespace std; 5 int pk[80]; 6 int pv[80],px[80]; 7 int dp[80][80][80][2]; 8 int vn = 0,kn = 0,xn = 0; 9 int vs[80],ks[80],xs[80];10 int N;11 string s;12 int get(int num,int flag,int v,int k,int x)13 {14 int ans = 0,tans[3];15 tans[0] = max(vs[num]-v,0);16 tans[1] = max(ks[num]-k,0);17 tans[2] = max(xs[num]-x,0);18 for (int i = 0;i<=2;i++)19 if (i!=flag) ans+=tans[i];20 return ans;21 }22 int main()23 {24 cin >> N;25 cin >> s;26 for (int i = 0 ;i