24h購物| | PChome| 登入
2012-09-19 20:32:55| 人氣1,373| 回應0 | 上一篇 | 下一篇

[UVA][dp][java] 10069 - Distinct Subsequences

推薦 0 收藏 0 轉貼0 訂閱站台

Problem E

Distinct Subsequences

Input: standard input

Output: standard output

 

A subsequence of a given sequence is just the given sequence with some elements (possibly none) left out. Formally, given a sequence X = x1x2xm, another sequence Z = z1z2zk is a subsequence of X if there exists a strictly increasing sequence <i1, i2, …, ik> of indices of X such that for all j = 1, 2, …, k, we have xij = zj. For example, Z = bcdb is a subsequence of X = abcbdab with corresponding index sequence < 2, 3, 5, 7 >.

In this problem your job is to write a program that counts the number of occurrences of Z in X as a subsequence such that each has a distinct index sequence.

 

Input

The first line of the input contains an integer N indicating the number of test cases to follow.

The first line of each test case contains a string X, composed entirely of lowercase alphabetic characters and having length no greater than 10,000. The second line contains another string Z having length no greater than 100 and also composed of only lowercase alphabetic characters. Be assured that neither Z nor any prefix or suffix of Z will have more than 10100 distinct occurrences in X as a subsequence.

 

Output

For each test case in the input output the number of distinct occurrences of Z in X as a subsequence. Output for each input set must be on a separate line.

 

Sample Input

2
babgbag
bag
rabbbit
rabbit

 

Sample Output

5
3

方程網路講得很清楚了, 就不描述了


import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int t;
        String a, b;
        t = cin.nextInt();
        while(t-- != 0) {
            a = cin.next();
            b = cin.next();
            int la = a.length(), lb = b.length();
            int i, j;
            BigInteger[][] dp = new BigInteger[la+1][lb+1];
            for(i = 0; i <= la; i++)
                dp[i][0] = BigInteger.valueOf(1);
            for(i = 1; i <= lb; i++)
                dp[0][i] = BigInteger.valueOf(0);
            for(i = 1; i <= la; i++) {
                for(j = 1; j <= lb; j++) {
                    if(i > 0)
                        dp[i][j] = dp[i-1][j];
                    if(a.charAt(i-1) == b.charAt(j-1))
                        dp[i][j] = dp[i][j].add(dp[i-1][j-1]);
                }
            }
            System.out.println(dp[la][lb]);
        }
    }
}

台長: Morris
人氣(1,373) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 10139 - Factovisors
此分類上一篇:[UVA][摸擬] 397 - Equation Elation

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文