跳到正文

题解

P1019 题解

RyanLi约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年2月18日
收录
2026年10月1日
更新
2026年11月8日
篇幅
约 2 分钟
获赞
72
题目
P1019

版本

  1. v1当前

传送门:P1019 [NOIP 2000 提高组] 单词接龙

更佳的阅读体验:洛谷 P1019 题解


题目没有给字符串的数据范围,但有 n≤20n \le 20,尝试搜索发现可以通过本题。

在搜索时处理重合部分为本题难点,需要留意截取字串的边界问题(即下文代码 dfs() 函数中的 ii 和 jj)。

C++
#include <iostream>
using namespace std;

const int N = 30;
int n, vis[N], ans;
string s[N];
char c;

void dfs(const string &tmp) {
    ans = max(ans, int(tmp.size()));
    for (int i = 1; i <= n; ++i) {
        if (vis[i] >= 2) continue;
        for (int j = 1; j < min(tmp.size(), s[i].size()); ++j)
            if (tmp.substr(tmp.size() - j) == s[i].substr(0, j)) {
                ++vis[i];
                dfs(tmp + s[i].substr(j));
                --vis[i];
            }
    }
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> s[i];
    cin >> c;
    for (int i = 1; i <= n; ++i) if (s[i][0] == c) {
        ++vis[i];
        dfs(s[i]);
        --vis[i];
    } cout << ans << '\n';
    return 0;
}
原文
存档评论37 条抓取于