2018 计蒜之道 复赛 G

本文介绍了一种解决贝壳找房计数比赛中特定问题的方法。该问题是:给定两个字符串s和t,求s的所有去重全排列中t出现的次数。文章提供了一个高效的算法实现,包括如何计算字符串s在去除子串t后的剩余部分的全排列,以及如何通过这些排列重新插入t来计算最终答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

题面:

贝壳找房举办了一场计数比赛,比赛题目如下。

给一个字符串 ss 和字符串 tt,求出 ss 的所有去重全排列中 tt 出现的次数。比如aab的去重全排列为aabababaa。注意aaaa算出现两次aaa

你的老大希望你帮他写一个程序作弊。

思路:

先在s串中删除t串得到m串,计算m串的去重全排列数量,然后在所有m串所有位置中插入t串,就能得到结果

代码:

#include<algorithm>
#include<typeinfo>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<stdio.h>
#include<math.h>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
#define pi acos(-1)
#define mod (1000000007)
#define fin(num,n) for(int aaa=0;aaa<n;cin>>num[aaa++])
#define fout(num,n) for(int aaa=0;aaa<n;cout<<num[aaa++]<<(aaa==n-1?'\n':' '))
#define ffin(num,n,m) for(int aaa=0;aaa<n;aaa++)for(int bbb=0;bbb<m;cin>>num[aaa][bbb++])
#define ffout(num,n,m) for(int aaa=0;aaa<n;aaa++)for(int bbb=0;bbb<m;cout<<num[aaa][bbb++]<<(bbb==m-1?'\n':' '))
ll gcd(ll x, ll y) { return x ? gcd(y%x, x) : y; }
ll lcm(ll x, ll y) { return x * y / gcd(x, y); }

ll T, jie[1000005];
string s, t;
void init() {
	jie[1] = 1;
	for (int a = 2; a < 1000001; a++)
		jie[a] = a * jie[a - 1], jie[a] %= mod;
}
ll suan(ll a, ll b) {
	ll ans = 1;
	while (b) {
		if (b & 1)
			ans *= a, ans %= mod;
		a *= a;
		a %= mod;
		b >>= 1;
	}
	return ans;
}

int main() {
	ios::sync_with_stdio(false);
	cout << fixed << setprecision(0);

	init();
	while(cin>>T)
		while (T--) {
			cin >> s >> t;
			int mp[30] = { 0 }, sum = 0;
			for (int a = 0; a < s.size(); a++)
				mp[s[a] - 'a']++;
			for (int a = 0; a < t.size(); a++)
				mp[t[a] - 'a']--;
			for (int a = 0; a < 30; a++)
				if (mp[a] < 0) {
					sum = -1;
					break;
				}
				else
					sum += mp[a];
			if (sum == -1)
				cout << 0 << endl;
			else if (sum == 0)
				cout << 1 << endl;
			else {
				ll ans = jie[sum];
				for (int a = 0; a < 29; a++)
					if(mp[a]>1)
						ans *= suan(jie[mp[a]], mod - 2), ans %= mod;
				ans *= sum+1;
				ans %= mod;
				cout << ans << endl;
			}
		}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值