2017微软秋季校园招聘在线编程笔试 题目2 Composition

http://hihocoder.com/contest/mstest2016oct/problem/2

一开始N*N一直超时,觉得不应该,然后java换成C++写了一下,还是TLE。各种地方改了一下,时间花了很多但依然还是大写的TLE。

后来想了一下,改成26*N总该可以了吧,然后ac了

题目2 : 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
java代码如下:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static int N,M;
	static int[][] map;
	static int[] numlist;
	static String str;
	static int res;
	static int[] dp;
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int a,b;
		while(sc.hasNext()){
			N=sc.nextInt();
			str=sc.next();
			numlist=new int[N];
			map=new int[26][26];
			dp=new int[26];
			for(int i=0;i<N;i++){
				numlist[i]=str.charAt(i)-'a';
			}
			M=sc.nextInt();
			for(int i=0;i<M;i++){
				str=sc.next();
				a=str.charAt(0)-'a';
				b=str.charAt(1)-'a';
				map[a][b]=1;
				map[b][a]=1;
			}
			for(int i=0;i<N;i++){
				if(dp[numlist[i]]>0){
					if(map[numlist[i]][numlist[i]]!=1) dp[numlist[i]]=dp[numlist[i]]+1;
				}
				else dp[numlist[i]]=1;
				for(int j=0;j<26;j++){
					if(map[numlist[i]][j]!=1&&dp[j]>0&&numlist[i]!=j){
						dp[numlist[i]]=Math.max(dp[numlist[i]], dp[j]+1);
					}
				}
			}
			res=1;
			for(int i=0;i<26;i++){
				res=Math.max(res, dp[i]);
			}
			System.out.println(N-res);
		}
	}

}





猜你喜欢

转载自blog.csdn.net/hqw11/article/details/52782520