URL: http://acm.hdu.edu.cn/showproblem.php?pid=6034
贴两个AC代码
#include<stdio.h>
#include<string.h>
int flag[26],ff[26],que[26],dat[26],u,maxlen;
typedef long long LL;
const LL MOD=1e9+7;
LL ANS[26];
const int MAXN=1e5+5;
char s[MAXN];
int mp[MAXN][26];
int power[MAXN];
bool cmp(int a,int b,int n){
for(int i=maxlen-1;i>=0;--i){
if(mp[i][a]!=mp[i][b]) return mp[i][a]>mp[i][b];
}
return false;
}
LL sum(int a,int n){
LL ss=0,one=1;
for(int i=0;i<maxlen;++i){
ss+=1LL*n*mp[i][a]*power[i];
ss%=MOD;
}
return ss;
}
int main()
{
power[0]=1;
for(int i=1;i<MAXN;++i) power[i]=1LL*26*power[i-1]%MOD;
int n,t=0;char c;
while(scanf("%d",&n)!=EOF){
maxlen=u=0;
memset(ff,0,sizeof(ff));
memset(mp,0,sizeof(mp));
memset(flag,0,sizeof(flag));
memset(dat,0,sizeof(dat));
memset(ANS,0,sizeof(ANS));
for(int i=0;i<n;++i){
scanf("%s",s);
int len=strlen(s);
if(maxlen<len) maxlen=len;
if(len>1) flag[s[0]-'a']=1;
for(int j=0;j<len;++j){
int pos=len-j-1;
++mp[pos][s[j]-'a'];
while(mp[pos][s[j]-'a']>=26){
mp[pos+1][s[j]-'a']+=mp[pos][s[j]-'a']/26;
mp[pos][s[j]-'a']%=26;
++pos;
}
if(pos+1>maxlen) maxlen=pos+1;
if(!ff[s[j]-'a']) ++u,ff[s[j]-'a']=1;
}
}
int o=0;
LL ans=0;
for(int i=0;i<26;++i) if(ff[i]) que[o++]=i;
for(int i=25;25-i+1<=u;--i){
int id=0;
for(int j=1;j<o;++j){
if(cmp(que[j],que[id],i)) id=j;
}
dat[i]=que[id];
ANS[que[id]]=sum(que[id],i);
ans+=ANS[que[id]];
ans%=MOD;
--o;
for(int j=id;j<o;++j){
que[j]=que[j+1];
}
}
if(u==26&&flag[dat[0]]){
int id=0;
while(flag[dat[id++]]){
ans+=MOD-ANS[dat[id]]+sum(dat[id-1],id);
ans%=MOD;
}
}
printf("Case #%d: %lld\n",++t,ans);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const LL MOD=1e9+7;
const int MAXN=1e5+5;
int flag[26],ff[26],que[26],power[MAXN],mp[MAXN][26],u,maxlen;
char s[MAXN];
bool cmp(int a,int b){
for(int i=maxlen-1;i>=0;--i){
if(mp[i][a]!=mp[i][b]) return mp[i][a]>mp[i][b];
}
return false;
}
LL sum(int a,int n){
LL ss=0,one=1;
for(int i=0;i<maxlen;++i){
ss+=1LL*n*mp[i][a]*power[i];
ss%=MOD;
}
return ss;
}
int main()
{
power[0]=1;
for(int i=1;i<MAXN;++i) power[i]=1LL*26*power[i-1]%MOD;
int n,t=0;char c;
while(scanf("%d",&n)!=EOF){
maxlen=u=0;
memset(ff,0,sizeof(ff));
memset(mp,0,sizeof(mp));
memset(flag,0,sizeof(flag));
for(int i=0;i<n;++i){
scanf("%s",s);
int len=strlen(s);
if(maxlen<len) maxlen=len;
if(len>1) flag[s[0]-'a']=1;
for(int j=0;j<len;++j){
int pos=len-j-1;
++mp[pos][s[j]-'a'];
while(mp[pos][s[j]-'a']>=26){
mp[pos+1][s[j]-'a']+=mp[pos][s[j]-'a']/26;
mp[pos][s[j]-'a']%=26;
++pos;
}
if(pos+1>maxlen) maxlen=pos+1;
if(!ff[s[j]-'a']) ++u,ff[s[j]-'a']=1;
}
}
for(int i=0,o=0;i<26;++i) if(ff[i]) que[o++]=i;
sort(que,que+u,cmp);
if(u==26&&flag[que[25]]){
int id=25;
while(flag[que[--id]]);
while(id<25){
que[id]=que[id+1];
++id;
}
}
LL ans=0;
for(int i=25;i>=26-u;--i){
ans+=sum(que[25-i],i);
ans%=MOD;
}
printf("Case #%d: %lld\n",++t,ans);
}
return 0;
}