Composition

题目1 : Composition

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

Alice writes an English composition with a length of N characters. However, her teacher requires that M illegal pairs of characters cannot be adjacent, and if 'ab' cannot be adjacent, 'ba' cannot be adjacent either.

In order to meet the requirements, Alice needs to delete some characters.

Please work out the minimum number of characters that need to be deleted.

输入

The first line contains the length of the composition N.

The second line contains N characters, which make up the composition. Each character belongs to 'a'..'z'.

The third line contains the number of illegal pairs M.

Each of the next M lines contains two characters ch1 and ch2,which cannot be adjacent.  

For 20% of the data: 1 ≤ N ≤ 10

For 50% of the data: 1 ≤ N ≤ 1000  

For 100% of the data: 1 ≤ N ≤ 100000, M ≤ 200.

输出

One line with an integer indicating the minimum number of characters that need to be deleted.

样例提示

Delete 'a' and 'd'.

样例输入

5
abcde
3
ac
ab
de

样例输出

2

由于删掉最少等价于留下最多,所以我们可以用f[i]表示最后留下一个字符是S[i]时,最多留下多少个字符。

要求f[i],我们只需要枚举S[i]之前的一个字符是哪个,并且从中选择合法并且最优的解:

f[i] = max{f[j]} + 1, for j = 1 .. i-1且S[j]S[i]不是"illegal pair"。

以上的DP解法是O(N^2)的,仍有优化的空间。

我们求f[i]时,需要枚举之前所有的位置j,但实际上之前的字符只有'a'~'z'26种可能。对于相同的字符,我们只用考虑最后一次它出现的位置,之前的位置一定不是最优。

例如,假设s[2] = s[5] = s[8] = 'h',那么当i>8时,我们求f[i]根本不用考虑j=2和j=5的情况,这两种情况即便合法也不会比j=8更优。

于是我们每次求f[i]只需要考虑'a'~'z'最后一次出现的位置。复杂度可以优化到O(26N)

import java.io.BufferedInputStream;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Stack;



public class Main {
	public static final int INF = 0x3f3f3f3f;
	public static Scanner in = new Scanner(new BufferedInputStream(System.in));
	public static void main(String[] args) {
		String string;
		boolean[][] map = new boolean[27][27];
		for(int i='a' ; i<='z' ; ++i)
			for(int j='a' ; j<='z' ; ++j)map[i-'a'][j-'a'] = true;
		in.nextLine();
		string = in.nextLine();
		while (string=="")string = in.nextLine();
		int k = in.nextInt();
		while (k-->0) {
			String string2 = in.nextLine();
			while (string2.equals(""))string2 = in.nextLine();
			int u = string2.charAt(0)-'a';
			int v = string2.charAt(1) - 'a';
			map[u][v] = map[v][u] = false;
		}
		System.out.println(new Solution(string, map).solve());
	}
}
class Solution {
	String string;
	boolean[][] map;
	int[] cnt;
    public Solution(String string, boolean[][] map) {
		super();
		this.string = string;
		this.map = map;
		cnt = new int['z'+10];
		for(int i='a' ; i<='z' ; ++i)cnt[i] =0;
	}
    
	public int solve() {
		for(int i=0 ; i

 

你可能感兴趣的:(dp,hihocode,java,算法,hihocoder)