[BNUZOJ][ACM][2014新生赛重现][现场]放课后茶会
Posted hdw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[BNUZOJ][ACM][2014新生赛重现][现场]放课后茶会相关的知识,希望对你有一定的参考价值。
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int length = sc.nextInt(); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(int i=0;i<length;i++){ sb1.append(sc.next()); } for(int i=0;i<length;i++){ sb2.append(sc.next()); } List<String> list = LCS(sb1.toString(),sb2.toString()); if(list.size() > 0){ String result = list.get(0); if(result.length() == sb1.length()){ System.out.println("^_^"); }else{ for(int i=0;i<result.length();i++){ System.out.print(result.charAt(i)); if(i<result.length()-1){ System.out.print(" "); } } System.out.println(); } }else{ System.out.println("T_T"); } } } public static List<String> LCS(String str1,String str2){ List<String> result = new ArrayList<String>(); int max = 0; int[][] dp = new int[str1.length()+1][str2.length()+1]; for(int i=0;i<=str1.length();i++){ dp[i][0] = 0; } for(int i=0;i<=str2.length();i++){ dp[0][i] = 0; } for(int i=1;i<=str1.length();i++){ for(int j=1;j<=str2.length();j++){ if(str1.charAt(i-1) == str2.charAt(j-1)){ dp[i][j] = dp[i-1][j-1] + 1; if(dp[i][j] >= max){ max = dp[i][j]; String s = str1.substring(i-max,i); while(result.size() > 0 && result.get(result.size()-1).length() < s.length()){ result.remove(result.size()-1); } result.add(s); } }else{ dp[i][j] = 0; } } } return result; } }
利用LCS求出最长公共子串即可
以上是关于[BNUZOJ][ACM][2014新生赛重现][现场]放课后茶会的主要内容,如果未能解决你的问题,请参考以下文章
HDU 5112 A Curious Matt (2014ACM/ICPC亚洲区北京站-重现赛)