单调栈思维 2021年度训练联盟热身训练赛第三场——K题Summer Trip
題意:
給你一個字符串,問其子串中有多少個滿足:
1.子串頭尾字母不相同;
2.子串內部字母與頭尾字母不相同;
3.子串長度大于等于2;
問有多少個這樣的字串?
題目:
Leo has started a job in a travel agency. His first task is to organize a summer trip to an exotic overseas city. During the summer season, events of various types take place in the city: sports matches, concerts, beach parties, and many others. At any given time, there is exactly one event taking place. Events of any particular type may take place more than once during the season. The itinerary of events that Leo offers to his clients cannot be chosen arbitrarily; the company requires them to form a so-called “good itinerary.” A good itinerary is a consecutive sequence of at least two events in the summer season, where the first and last events are of different types, and they are both unique among all event types during the sequence. For example, if the first event in a good itinerary is a beach party, none of the other events during the itinerary can also be a beach party. There are no other restrictions on the event types in the sequence of a good itinerary.
Before he starts organizing the trip, Leo wants to know the total number of good itineraries that are possible given a calendar of events that will take place over the summer season.
輸入描述:
The input consists of one line with a string describing the sequence of event types in the summer season. All characters are lowercase English letters (a - z)(a?z), with different letters represent different types of events. Character ii of the string encodes the ii-th event of the summer. There are no blanks or spaces in the string.
The length of the input string is at least 22 and at most 100 000100000 characters.
輸出描述:
Print the number of good itineraries that exist for the given summer season.
示例1
輸入
abbcccddddeeeee
輸出
10
示例2
輸入
thenumberofgoodstringsis
輸出
143
分析:
由題意我們很容易可以得出:
1.連續重復字母是沒有意義的,只有第一個字母起作用,其他重復因題目條件字串內部不能和子串首位相同,滿足題意只有兩種情況:1.連續重復的某字母在子串內;2.只有一個字母為首或尾,所以可以用set去重,找不重復字母;
2.當之前遍歷的字母中存在重復,
例如:thenumbe
那么對于最后一個e來說,求得是字符串numbe的子串滿足題意;
3.類單調棧思維,將一個字母,入所有字母的棧中,當遍歷到某字母時,加上set去重后的有效前綴的長度即可,維護有效前綴的方法是,由于上一次字母及其前綴都是不可用的,當遍歷到某字母加和后,直接清空棧即可。
AC代碼:
#include<stdio.h> #include<string.h> #include<stack> #include<set> #include<vector> #include<algorithm> using namespace std; const int maxn=1e5+10; char a[maxn]; int main() {int l;int ans=0;scanf("%s",a);set<int >s[30];l=strlen(a);for(int i=0;i<l;++i){int x=a[i]-'a'+1;ans+=s[x].size();for(int j=1;j<=26;++j)s[j].insert(x);s[x].clear();}printf("%d\n",ans);return 0; }總結
以上是生活随笔為你收集整理的单调栈思维 2021年度训练联盟热身训练赛第三场——K题Summer Trip的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 结构型模式——适配器模式
- 下一篇: Python安装及环境变量的配置