P1019 [NOIP2000 提高组] 单词接龙


原题链接

P1019
题目类型: 普 及 / 提 高 − {\color{yellow} 普及/提高-} /

题目大意

给你 n ≤ 20 n\le 20 n20个单词,让你串在一起,还规定单词串的开头字母为 c c c,每个单词最多用 2 2 2次,且相邻的两个单词不能是包含关系,求最长的单词串的长度。
S a m p l e \mathbf{Sample} Sample I n p u t \mathbf{Input} Input

5      //n
at
touch
cheat
choose
tact
a      //c

S a m p l e \mathbf{Sample} Sample O u t p u t \mathbf{Output} Output

23

H i n t & E x p l a i n \mathbf{Hint\&Explain} Hint&Explain

最长的单词串为:atoucheatactactouchoose

解题思路

d f s dfs dfs,把所有的可能性遍历,并维护当前已经连成的单词串和刚才连到单词串上的单词,再处理一下合并的函数和判断是否可以连上的函数即可

上代码

#include<iostream>
using namespace std;

int n,used[30],res;
string s[30];
char sta;

bool exist(string word,string b)
{
    // cout<<"exist:"<<word<<" "<<b<<endl;
    int fin;
    for(int i=1; i<word.size(); i++)
    {
        string str=word.substr(word.size()-i,i);
        fin=b.find(str);
        if(fin==0) return true;
    }
    return false;
}

string hebin(string a,string b)
{
    // cout<<"hebin:"<<a<<" "<<b<<endl;
    int fin,len=0;
    do
    {
        len++;
        string str=a.substr(a.size()-len,len);
        // cout<<len<<" "<<str<<endl;
        fin=b.find(str);
    }while(fin!=0);
    string str=a.substr(0,a.size()-len);
    return str+b ;
}

void dfs(string tar,string last)
{
    // cout<<tar<<" "<<last<<endl;
    bool can=false;
    for(int i=1; i<=n; i++)
        if(used[i]<2&&exist(last,s[i]))
        {
            can=true;
            used[i]++;
            dfs(hebin(tar,s[i]),s[i]);
            used[i]--;
        }
    if(!can)
    {
        int len=tar.size();
        res=std::max(res,len);
        // cout<<tar<<endl;
    }
}

int main()
{
    cin>>n;
    for(int i=1; i<=n; i++) cin>>s[i];
    cin>>sta;
    for(int i=1; i<=n; i++)
    {
        if(s[i][0]==sta)
        {
            used[i]++;
            dfs(s[i],s[i]);
            used[i]--;
        }
    }
    cout<<res<<endl;
    // cout<<hebin(s[1],s[1])<<endl;
    return 0;
}

完美切题 ∼ \sim

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值