Description
有 n n 个只由小写字母组成的字符串,两个人轮流从一个空字符串开始构造字符串,要求每个人在其操作轮要加一个字符在已有字符串前面或者后面使得这个字符串依旧是这个字符串中某些字符串的子串,如果没有合法方案则该人失败,否则该人得分,假设该人操作后字符串为 s s ,则本轮得分,其中 value(c) v a l u e ( c ) 为 c c 在个字母中的位置,即 value(′a′)=1,value(′z′)=26 v a l u e ( ′ a ′ ) = 1 , v a l u e ( ′ z ′ ) = 26 , num(s) n u m ( s ) 为这 n n 个字符串中以为子串的字符串数量,每个人在操作时采取最优策略让自己赢,且在保证自己赢的情况下使得自己得分最高,在保证自己赢且得分最高的情况下使得对方得分尽可能少,问最后哪一个人赢以及两个人的得分
Input
第一行一整数 n n 表示字符串数量,之后输入个长度不超过 30 30 且只由小写字母组成的字符串 (1≤n≤30) ( 1 ≤ n ≤ 30 )
Output
输出哪一个人赢以及两个人的得分
Sample Input
2
aba
abac
Sample Output
Second
29 35
Solution
由于字符串数量和长度都不超过 30 30 ,不同子串数不多,预处理出每个子串的 value v a l u e 和 num n u m ,之后对所有可能的情况记忆化搜索即可,对于一个字符串,记录从该字符串开始操作,先手是否必胜以及两人的得分,枚举加的字符和位置转移,用后继状态更新当前状态,先让自己赢,然后让自己得分尽可能多,然后让对方得分尽可能少,以此选取最优状态记录
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
struct P
{
int sg,first,second;
P(){};
P(int _sg,int _first,int _second)
{
sg=_sg,first=_first,second=_second;
}
bool operator<(const P&b)const
{
if(sg!=b.sg)return sg<b.sg;
if(first!=b.first)return first<b.first;
return second>b.second;
}
};
set<string>S;
map<string,P>M;
map<string,int>Num;
int Score(string s)
{
int ans=0,mx=0;
for(int i=0;i<s.length();i++)
{
ans+=s[i]-'a'+1;
mx=max(mx,s[i]-'a'+1);
}
return ans*mx+Num[s];
}
P dfs(string s)
{
if(M.find(s)!=M.end())return M[s];
P ans=P(0,0,0);
for(int i=0;i<26;i++)
{
string ss=s+char('a'+i);
if(S.find(ss)!=S.end())
{
P temp=dfs(ss);
swap(temp.first,temp.second);
temp.sg^=1;
temp.first+=Score(ss);
if(ans<temp)ans=temp;
}
ss=char('a'+i)+s;
if(S.find(ss)!=S.end())
{
P temp=dfs(ss);
swap(temp.first,temp.second);
temp.sg^=1;
temp.first+=Score(ss);
if(ans<temp)ans=temp;
}
}
return M[s]=ans;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
string s;
cin>>s;
set<string>sub;
for(int l=0;l<s.length();l++)
for(int r=l;r<s.length();r++)
{
string ss=s.substr(l,r-l+1);
S.insert(ss);
if(sub.find(ss)==sub.end())
{
sub.insert(ss);
Num[ss]++;
}
}
}
P ans=dfs("");
if(ans.sg)printf("First\n");
else printf("Second\n");
printf("%d %d\n",ans.first,ans.second);
return 0;
}