Codeforces Round #265 (Div. 1) C. Substitutes in Number dp

题目链接:

http://codeforces.com/contest/464/problem/C

J. Substitutes in Number

time limit per test 1 second
memory limit per test 256 megabytes
#### 问题描述 > Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007 (109 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero. > > Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him! #### 输入 > The first line contains string s (1 ≤ |s| ≤ 105), consisting of digits — the string before processing all the requests. > > The second line contains a single integer n (0 ≤ n ≤ 105) — the number of queries. > > The next n lines contain the descriptions of the queries. The i-th query is described by string "di->ti", where di is exactly one digit (from 0 to 9), ti is a string consisting of digits (ti can be an empty string). The sum of lengths of ti for all queries doesn't exceed 105. The queries are written in the order in which they need to be performed. #### 输出 > Print a single integer — remainder of division of the resulting number by 1000000007 (109 + 7). #### 样例 > **sample input** > 123123 > 1 > 2->00 > > **sample output** > 10031003

题意

每次选择选择一个数字,把所有出现这个数字的地方替换成一串数字。问你求最后这个数%10^7的结果。

题解

如果我们模拟去做,相当于是做了一次搜索,每个出现这个数字的地方我们就要执行一次替换,而且这个替换还不一定是最后的结果,它有可能生出更多的替换(相当于是没有解决的重叠子问题!!!),自然时间上回承受不了。
但是如果我们采用dp的思想,从下往上做上来,我们解决了一个子问题,在所有用到这个子问题的时候,都只要直接调用就可以了。
还需要一些位权展开的知识,脑补一下。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
using namespace std;

const int maxn = 1e5 + 10;
const int mod = 1e9 + 7;
typedef __int64 LL;
int n;

char str[maxn],s[maxn];

LL pw[22], val[22];

int ql[maxn];
string qr[maxn];
map<char, int> mp;
int main() {
	scanf("%s", &str);
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%s", s);
		ql[i] = s[0]-'0';
		qr[i] = s + 3;
	}
	for (int i = 0; i < 10; i++) {
		pw[i] = 10; val[i] = i;
	}
	for (int i = n - 1; i >= 0; i--) {
		LL sum = 0, tpw = 1;
		for (int j = 0; j < qr[i].length(); j++) {
			LL num = qr[i][j] - '0';
			sum = (sum*pw[num] + val[num]) % mod;
			tpw = tpw*pw[num] % mod;
		}
		val[ql[i]] = sum;
		pw[ql[i]] = tpw;
	}
	LL ans = 0;
	int len = strlen(str);
	for (int i = 0; i < len; i++) {
		int num = str[i] - '0';
		ans = (ans*pw[num] + val[num]) % mod;
	}
	printf("%I64d
", ans);
	return 0;
}
原文地址:https://www.cnblogs.com/fenice/p/5700637.html