RQNOJ 429 词链:单调栈

题目链接:https://www.rqnoj.cn/problem/429

题意:

  如果一张由一个词或多个词组成的表中,每个单词(除了最后一个)都是排在它后面的单词的前缀,则称此表为一个词链。

  如:i,int,integer.

  给你一堆按字典序排好的字符串,问你最长的词链有多长(词链中的字符串个数)。

 

题解:

  单调栈。

  

  找出单调性:

    对于栈内的元素,从栈底到栈顶为单调,形成一个词链。

  

  找出答案:

    扫一遍给出的字符串,栈的最大高度即为答案。

 

  维护单调性:

    因为字符串按字典序排好,已经达到了是单调性最优的状态(贪心证明),所以就不用管扫描顺序了。

    对于一个新扫到的字符串s[i]:

      (1)如果满足单调性,则入栈。

        即:1. 当前栈顶为s[i]的前缀(is_prefix(stk.top(),s[i]))。

          2. 当前栈为空。

      (2)如果不满足单调性,则弹出栈顶,直到满足单调性为止。

 

AC Code:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <stack>
 5 #define MAX_N 10005
 6 
 7 using namespace std;
 8 
 9 int n;
10 int ans;
11 string s[MAX_N];
12 stack<string> stk;
13 
14 void read()
15 {
16     cin>>n;
17     for(int i=0;i<n;i++)
18     {
19         cin>>s[i];
20     }
21 }
22 
23 bool is_prefix(string sub,string dst)
24 {
25     if(sub.size()>dst.size()) return false;
26     for(int i=0;i<sub.size();i++)
27     {
28         if(sub[i]!=dst[i]) return false;
29     }
30     return true;
31 }
32 
33 void solve()
34 {
35     ans=0;
36     for(int i=0;i<n;i++)
37     {
38         while(!stk.empty() && !is_prefix(stk.top(),s[i]))
39         {
40             stk.pop();
41         }
42         stk.push(s[i]);
43         ans=max(ans,(int)stk.size());
44     }
45 }
46 
47 void print()
48 {
49     cout<<ans<<endl;
50 }
51 
52 int main()
53 {
54     read();
55     solve();
56     print();
57 }

 

 

posted @ 2017-08-31 23:59  Leohh  阅读(120)  评论(0编辑  收藏  举报