跳到正文

题解

题解:P17828 [CSP-J 2026] 回文串 / string(民间数据)

LS185约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月31日
收录
2026年10月31日
更新
2026年11月7日
篇幅
约 4 分钟
题目
P17828

版本

  1. v1当前

上午考试,下午写题解。
贪心的思想:

枚举给出的字符串s,对于s[i] (i=0,1,2,……,n-1) 均要满足:

s[i]=s[n−i−1]s[i] = s[n-i-1]

首先是暴力

直接构造字符串,逐个判断i (i=0,1,2,……,len/2+1)是否满足条件

C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    int n;
    cin >> n;
    string s;
    for (int i = 1; i <= n; ++i) {
        long long cnt;
        char ch;
        cin >> cnt >> ch;
        for (long long j = 0; j < cnt; j++) {
            s += ch;
        }
    }
    long long L = s.size();
    long long ans = 0;
    for (long long i = 0; i < L / 2; ++i) {
        long long j = L - i - 1;
        if (s[i] != s[j]) {
            ans++;
        }
    }
    cout << ans << endl;
    return 0;
}

明显地,时间复杂度为 O(max(a[1],a[2]……a[n])∗n)O(max(a[1],a[2]……a[n]) * n)

优化

将存储的方式改成结构体数组

C++
struct Block {
    long long len;
    char ch;
};

再用双指针: l=1,r=n;

C++
while (l < r) {
  ll take = min(remL, remR);
  if (b[l].ch != b[r].ch) {
  ans += take;
  }
  remL -= take;
  remR -= take;
  if (remL == 0) {
       l++;
       remL = b[l].len;
  }
  if (remR == 0) {
      r--;
      remR = b[r].len;
  }
}

正确代码

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

struct Block {
    ll len;
    char ch;
};

const int N = 200010;
Block b[N];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> b[i].len >> b[i].ch;
    }
    int l = 1, r = n;
    ll remL = b[l].len;
    ll remR = b[r].len;
    ll ans = 0;
    while (l < r) {
        ll take = min(remL, remR);
        if (b[l].ch != b[r].ch) {
            ans += take;
        }
        remL -= take;
        remR -= take;
        if (remL == 0) {
            l++;
            remL = b[l].len;
        }
        if (remR == 0) {
            r--;
            remR = b[r].len;
        }
    }
    cout << ans << endl;
    return 0;
}

后记

考场上差点没写出来……

原文