---
id: 159
lang: en
translation_of: index.md
source_sha256: 51010aff9a2dd36e07f3d3ae91c11ae80387e73aec863c5d4496af8a57790c6d
title: "P1666: Prefix Words — Solution"
description: "Precompute which pairs of words are safe, sort the strings so the DP has no aftereffects, then run a one-dimensional DP."
tags: ["OI","DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Approach

This is a dynamic programming problem. We first consider preprocessing an array that stores whether each pair of words is safe. Then we use this information to do the DP. One point worth noting: when doing dynamic programming we have to eliminate aftereffects, otherwise we will get wrong answers. In this problem, we need to sort the strings, because after sorting, the unsafe words only exist before the $i$-th word, so a one-dimensional $dp$ is enough. Consider the equation: $dp[j] += dp[i], j \in [i, n], possible[i][j] == true$, and that's it.

<!--more-->

## Code

```cpp
// P1666.cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 60;
string dict[maxn];
long long n, dp[maxn], current;
bool possible[maxn][maxn];
bool isPrefix(string a, string b)
{
    if (b.length() > a.length())
        swap(a, b);
    return (a.find(b) == 0);
}
int main()
{
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
        cin >> dict[i];
    sort(dict + 1, dict + n + 1);
    for (int i = 1; i <= n; i++)
    {
        dp[i] = 1;
        for (int j = 1; j <= n; j++)
            if (!isPrefix(dict[i], dict[j]))
                possible[i][j] = possible[j][i] = true;
    }
    long long ans = 0;
    for (int i = 1; i <= n; i++)
        for (int j = i; j <= n; j++)
            if (possible[i][j])
                dp[j] += dp[i];
    for (int i = 1; i <= n; i++)
        ans += dp[i];
    printf("%lld", ans + 1);
    return 0;
}
```
