programming-challenges Distinct Subsequences (111102) 题解

大数问题。加上一个处理大数的方法就在uva和code challenge上都ac了

<pre name="code" class="cpp">#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

const int N = 10010; 
const int M = 110;

struct BigNum {
	string val; 

	BigNum() {}
	BigNum(string s) { 
		val = s;
	}
};

ostream& operator<<(ostream& o, BigNum& bn) {
	o << bn.val;
	return o; 
}

BigNum operator+ (const BigNum& bn1, const BigNum& bn2) {
	BigNum result; 
	int l1 = bn1.val.length() - 1;
	int l2 = bn2.val.length() - 1;
	int jie = 0; 
	while (l1 >= 0 || l2 >= 0) {
		int v1 = 0, v2 = 0; 
		if (l1 >= 0) v1 = bn1.val[l1] - '0';
		if (l2 >= 0) v2 = bn2.val[l2] - '0';
		int v = v1 + v2 + jie; 
		if (v >= 10) {
			jie = 1; 
			v -= 10; 
		}
		else {
			jie = 0;
		}

		result.val.insert(result.val.begin(), '0' + v); 

		l1--; 
		l2--;
	}
	if (jie > 0) result.val.insert(result.val.begin(), '1');
	return result;
}

BigNum num[N][M];

int main() {
	int n; cin >> n; 
	for (int tc = 0; tc < n; tc++) {
		string s1, s2; cin >> s1 >> s2; 

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				num[i][j].val.clear();
			}
		}
		
		for (int i = 1; i <= s1.size(); i++) {
			if (s2[0] == s1[i - 1]) {
				num[i][1] = num[i - 1][1] + BigNum("1"); 
			}
			else {
				num[i][1] = num[i - 1][1];
			}
		}

		for (int i = 2; i <= s2.size(); i++) {
			for (int j = i; j <= s1.size(); j++) {
				if (s2[i-1] == s1[j-1]) {
					num[j][i] = num[j - 1][i - 1] + num[j - 1][i]; 
				}
				else {
					num[j][i] = num[j - 1][i];
				}
			}
		}

		cout << num[s1.size()][s2.size()] << endl;
	}

	

	return 0; 
}


 
 

你可能感兴趣的:(Algorithm,C++)