数据结构---栈(STL)

本文介绍了一个使用STL栈实现的接龙游戏代码,通过排序和栈操作来找出字符串数组中最长的有效接龙序列。该算法首先将输入字符串按字典序排序,然后利用栈的数据结构来检查是否能形成有效的接龙。

codevs1051接龙游戏

第一次用STL写了写“栈”

表示还需要再多看看理解理解。

 1 #include<iostream>
 2 #include<stack>//STL栈
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int main()
 7 {
 8     string A[100005];//二维 
 9     int n;
10     cin>>n;
11     for(int i=0;i<n;i++)
12     cin>>A[i];//二维字符串  这下懂了吧
13     int ans=1,maxn=1;
14     sort(A,A+n);//直接按字典序排。。。! 
15     /*!stack<int>s*/
16     stack<string>sta;//
17     sta.push(A[0]);//sta[1]=A[0];
18     for(int i=1;i<n;i++)
19     {
20         string New=A[i];
21         bool F=true;
22         while(1)
23         {
24             F=true;
25             if(sta.empty())
26             {
27                 sta.push(New);
28                 ans=1;
29                 break;
30             }
31             else
32             {
33                 string top=sta.top();//top   ...top这样也可以  好吧
34                 int num=top.size();//(string)  size==strlen 
35                 for(int i=0;i<num;i++)  //new的长度>=top的长度 
36                 {
37                     //F&=top[i]==New[i];
38                     if(top[i]!=New[i]) F=false;  
39                 }
40                 if(F&&New!=top)//two words are jielong.&&two words are different.
41                 {
42                     sta.push(New);
43                     ans++;
44                     break;
45                 }
46                 else{
47                     sta.pop();
48                     ans--;
49                 }
50             }
51         }
52         maxn=max(maxn,ans);
53     }
54     cout<<maxn<<endl;
55     return 0;
56  } 

 

 

转载于:https://www.cnblogs.com/babyyang/p/5281889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值