Chef and Sign Sequences

题目描述

Chef found a strange string yesterday – a string of signs $s$, where each sign is either a ‘<‘, ‘=’ or a ‘>’. Let $N$ be the length of this string. Chef wants to insert $N+1$ positive integers into this sequence and make it valid. A valid sequence is a sequence where every sign is preceded and followed by an integer, and the signs are correct. That is, if a sign ‘<‘ is preceded by the integer $a$ and followed by an integer $b$, then $a$ should be less than $b$. Likewise for the other two signs as well.
Chef can take some positive integers in the range $[1, P]$ and use a number in the range as many times as he wants.
Help Chef find the minimum possible $P$ with which he can create a valid sequence.

题意概述

给定一个由'<‘、’=’和’>’组成的字符串,要求在首尾和每两个相邻的符号间填入一个数,使得表达式成立。求数字的最小种类数。
数据范围:$1 \le |s| \le 10^5$。

算法分析

将’=’删去后,计算出只由'<‘或’>’组成的最长连续子串的长度,加$1$即得到答案。证明如下:

‘=’对最终结果没有影响,可以全部忽略。设找到了一个只由'<‘或’>’组成的最长连续子串,长度为$l$。在这个子串的左边填入$a$,右边填入$a+l$。由于其他只由'<‘或’>’组成的连续子串的长度均不大于$l$,因此也可以分别在它们左右填入$a$和$a+l$,这样必定可以满足题目要求。

由此得证。

代码

#include <iostream>
#include <algorithm>
using namespace std;
int n, ans, len, out;
string s;
int main()
{
  cin >> n;
  while (n--) {
    cin >> s;
    ans = out = 0;
    len = s.length();
    for (int i = 0; i < len; ++i) {
      if (s[i] == '<') {
        if (ans < 0) ans = 0;
        ++ans;
      }
      if (s[i] == '>') {
        if (ans > 0) ans = 0;
        --ans;
      }
      out = max(out, abs(ans) + 1);
    }
    cout << out << endl;
  }
  return 0;
}

RegMs If

418 I'm a teapot

Leave a Reply

Your email address will not be published. Required fields are marked *