UVa 10069 Distinct Subsequences 简单dp+java大数

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1010

题意:给定母串和子串,问子串在母串中出现的次数

思路:

对于子串每一位u,记录能转移到u的(在母串中的位置)所有位置,存在S栈中

如此转移即可。

结果比较大会超int 64位

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

public class Main {
	static BigInteger[][]  dp = new BigInteger[2][10010];
	static void init(int x, int n){
		for(int i = 0; i <= n; i++)dp[x][i] = BigInteger.ZERO;
	}
	public static void main(String[] args){
		Scanner cin = new Scanner(System.in);
		
		int t = cin.nextInt();
	for(int dd = 0; dd < t; dd++){
	 	int[] S = new int[10010];
	 	int[] T = new int[10010];
	 	int tops = 0, topt = 0;
	 	char a[] = cin.next().toCharArray();
	 	char b[] = cin.next().toCharArray();
	 	init(0,a.length); init(1,a.length);
	 	int cur = 0;
	 	for(int i = 0; i < a.length; i++)if(a[i]==b[0])
	 		{ dp[0][i] = BigInteger.valueOf(1); S[tops++] = i; }
	 	
		for(int i = 1; i < b.length; i++){
			cur^=1;
			init(cur, a.length);	
			for(int j=0; j < a.length; j++)if(a[j]==b[i])
			{
				for(int k = 0; k < tops; k++)
				{
					int z = S[k]; if(z>=j)break;
					dp[cur][j] = dp[cur^1][z].add(dp[cur][j]);
					if(topt == 0 || T[topt-1]!=j) 
					T[topt++] = j;
				}
			}
			tops = 0;
			for(int k = 0; k < topt; k++)S[tops++]= T[k];
			topt = 0;
		}
		BigInteger ans = new BigInteger("0");
		for(int i = 0; i < a.length; i++)ans = ans.add(dp[cur][i]);
		System.out.println(ans);
	}
	 	
	}
}

附C代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <set>
#include <vector>
using namespace std;
#define ll long long
#define N 10005
ll dp[2][N];
char s[N], d[N];
vector<ll>G, P;
void init(ll x){
	memset(dp[x], 0, sizeof(dp[x]));
}

int main(){
	ll T, i, j, k;;scanf("%lld",&T);
	while(T--){
		G.clear(); P.clear(); init(0);init(1);
		scanf("%s",s);scanf("%s",d); 
		if(strlen(d)>strlen(s)){puts("0");continue;}
		ll cur = 0;		
		for(i=0;s[i]; i++)if(s[i]==d[0])dp[0][i] = 1, G.push_back(i);

		for(i = 1; d[i]; i++){
			cur^=1;
			init(cur);	
			for(j=0; s[j]; j++)if(s[j]==d[i])
			{
				for(k = 0; k < G.size(); k++)
				{
					ll z = G[k]; if(z>=j)break;
					dp[cur][j] += dp[cur^1][z];
					if(P.size() == 0 ||P[P.size()-1]!=j) 
					P.push_back(j);
				}
			}
			G.clear();
			for(k = 0; k < P.size(); k++)G.push_back(P[k]);
			P.clear();
		}
		ll ans = 0;
		for(i = 0; s[i]; i++)ans += dp[cur][i];
		printf("%lld\n",ans);
	}
	return 0;
}
/*
99
babgbag
bag
rabbbit
rabbit
aaa
aa
aaaa
aa
aaaa
aaa
aaaa
aaaa
aaabbb
aa
aaabbb
ab
aaabbbcc
abc

aaacccbbbccc

abbc

*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值