NAIPC 2018 Prefix Free Code
题意:给你n个字符串,给你一个k,意思是你能任选k个字符串组成一个长字符串。再给你一个长字符串问你这个字符串在所有任选k个字符串组合中字典序排第几。(所有字符串长度之和不大于1e6 , 要求结果对1e9 + 7取模)
这是我和左学长精诚合作弄出的一道题(虽然我的代码后面到处有坑)
字典树+dfs序(字典序大小)+树妆数组+阶乘计算答案
因为保证每一个字符串都不是其他串的前缀,那么在字典树上,每一条支链的结尾有且仅代表一个串,也就是说保证扫到串的末尾时,不会有其他串在这条链上。然后用一个 tpos[ ] 数组记录当前这个字典树的节点所代表的是输入的第几个串
字典树建好以后,用左学长优越的思想,用栈来做所有字符串的字典序排列,求得排名 dfn[ ] 数组
最后就是计算答案了
对于 n=7 k=5;
假设拼接的串的排列为(用字典序的排名表示) 3 5 4 7 1
对于首位为1或2的序列有 2 * (6 * 5 * 4 * 3 )
对于第二位为1~4的序列有 3 * (5 * 4 * 3 ) 这里不用4来乘的原因是 前面的3被首位占用了,所以无法再使用,故只剩下了三个数
对于第三位为1~3的序列为 2 * (4 * 3 )与上同理
其余以此类推
注意,由于前面预处理的阶乘,所以之后需要求逆元来计算答案;
上代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+7,mode=1e9+7;
int n,k;
int c[maxn];
char str[maxn];
vector<int> ans;
namespace s
{
int data[maxn],t;
void push(int x) { data[t++]=x; }
int pop() { return data[--t]; }
}
namespace trie
{
int tree[maxn][26],tot=0,dfn[maxn],tpos[maxn];
int dfs_num=0;
void build(int now){
int l=strlen(str),root=0;
for(int i=0;i<l;i++){
int id=str[i]-'a';
if(!tree[root][id])
{
tree[root][id]=++tot;
memset(tree[tot],0,sizeof(tree[tot]));
tpos[tot]=0;
}
root=tree[root][id];
}
tpos[root]=now;
}
void bfs(int root) {
s::t=0;
s::push(root);
int fr;
while(s::t)
{
fr=s::pop();
if(tpos[fr])
{
dfn[tpos[fr]]=++dfs_num;
continue;
}
for(int i=25;i>=0;--i){
if(tree[fr][i])
s::push(tree[fr][i]);
}
}
}
void query() {
int l=strlen(str),root=0;
for(int i=0;i<l;++i)
{
int id=str[i]-'a';
root=tree[root][id];
if(tpos[root])
{
ans.push_back(dfn[tpos[root]]);
root=0;
continue;
}
}
}
}
namespace T
{
int lowbit(int x){
return x&-x;
}
void add(int pos){
for(;pos<=n;pos+=lowbit(pos))
c[pos]++;
}
int findsum(int pos){
int ans=0;
for(;pos;pos-=lowbit(pos))
ans+=c[pos];
return ans;
}
}
ll quick_pow(ll base,ll ind)
{
ll ans=1;
while(ind)
{
if(ind&1) ans=ans*base%mode;
(base*=base)%=mode;
ind>>=1;
}
return ans;
}
ll multi[maxn];
void init()
{
trie::tot=trie::dfs_num=0;
memset(trie::tree[0],0,sizeof(trie::tree[0]));
ans=vector<int>();
fill(c,c+n,0);
}
int main(){
for(int i=multi[0]=1;i<maxn;++i)
multi[i]=multi[i-1]*i%mode;
while(~scanf("%d %d",&n,&k))
{
init();
for(int i=1;i<=n;i++){
scanf("%s",str);
trie::build(i);//字典树建树
}
trie::bfs(0);//求字典序
scanf("%s",str);
trie::query();
ll sum=0;
for(int i=0;i<ans.size();++i)
{
int used=T::findsum(ans[i]-1);//树状数组查询当前前面有多少个被用过的数
sum+=(ans[i]-1-used)*(multi[n-i-1]*quick_pow(multi[n-k],mode-2)%mode)%mode;
//quick_pow快速幂求逆元,因为这个在之前取了模所以一定得求逆元
sum%=mode;
T::add(ans[i]);
}
printf("%lld\n",(sum+1)%mode);
}
}
嗯嗯,团队合作写题目,真实,但是我还得在加强些思维训练啊,不然老是左学长来想题目,那我自己以后单打独斗就不行了呀!