为什么dfs可以在10ms内高效的过其他的点却过不了#2
查看原帖
为什么dfs可以在10ms内高效的过其他的点却过不了#2
1074084
asd890123楼主2024/6/22 09:04

亲测dfs其他点都10ms内过了,包括n=2000的,但是为啥#2没过(TLE1.2s+),疑问的code:

#include <algorithm>
#include <iostream>
#include <string>

int n,ans = 0x80000000;
std::string words[2005];

bool is_prefix(std::string s,std::string str){return str.find(s) == 0;}

void dfs(int x,std::string last,int amount){

    ans = std::max(amount,ans);
    if (x > n) return;
    dfs(x + 1,last,amount);
    if (x == 1 || is_prefix(last,words[x])) dfs(x + 1,words[x],amount + 1);

}

int main(){

    #ifndef ONLINE_JUDGE
        freopen("word.in","r",stdin);
    #endif

    std::cin.tie(0)->sync_with_stdio(0);

    std::cin >> n;
    for (int i = 1;i <= n;i++) std::cin >> words[i];
    std::sort(words + 1,words + 1 + n);
    dfs(1,"",0);
    std::cout << ans << '\n';

    return 0;
}
2024/6/22 09:04
加载中...