2026 CSP-J Round2 T2 回文串 / string 题解

explorer394 Lv1 新手 · 82 · 2026-12-06 13:38 精选
<!--StartFragment--><p style="margin-top: 0px; margin-bottom: 16px; padding: 0px; color: rgb(28, 25, 23); font-family: &quot;Helvetica Neue&quot;, &quot;Luxi Sans&quot;, &quot;DejaVu Sans&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft Yahei&quot;, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Noto Color Emoji&quot;, &quot;Segoe UI Symbol&quot;, &quot;Android Emoji&quot;, EmojiSymbols; font-variant-ligatures: no-common-ligatures; letter-spacing: -0.15px;"><br></p><!--EndFragment-->~~蒟蒻第一次写题解。~~<p><a href="https://www.luogu.com.cn/problem/P17828">题目传送门</a></p> <h2>题意概括</h2> <p>给定 $n$ 个字符串,求将其拼接后任意更改字符的情况下,转换为回文串的最小操作步数。</p> <h2>思路</h2> <p>首先不难发现,对于一个非回文串,如果要通过任意更改字符变成回文串,最小操作数量应当为左右两边字符不相同的数量。(后附正确性证明)</p> <p>但是本题并没有直接给字符串 $s$,而是给了它的具体组成,因此应当从两边开始处理组成,若有字符余下,则不往里缩进,而是减少字符数量(题目中的 $a_i$)。</p> <p>考虑双指针做法。左指针 $l$ 与右指针 $r$ 分别往内部缩进,超越时即为边界。</p> <p>特别的,若两边数量恰好相等,两边都需要缩进。</p> <p>最坏情况下答案约为 $\frac{1}{2}\sum a_i \le \frac{1}{2}\times 2\times10^5\times10^9=10^{14}$,超过 <code>int</code> 范围,需用 <code>long long</code>。</p> <p>AC代码如下:</p> <pre><code class="language-cpp">#include&lt;bits/stdc++.h&gt; using namespace std; int a[200005];char c[200005]; int main(){ ios::sync_with_stdio(0); cin.tie(nullptr); int n;long long ans=0;cin&gt;&gt;n; //答案可以达到10^14量级,注意long long for(int i=0;i&lt;n;i++) cin&gt;&gt;a[i]&gt;&gt;c[i]; int l=0,r=n-1; while(l&lt;=r){ //边界,l&lt;r也可以,因为l==r时c[l]==c[r],不做任何处理 if(a[l]&lt;a[r]){ //对左、右指针处数量的比较 ans+=(c[l]==c[r]?0:a[l]); //只有在字符不一致时才记录操作次数 a[r]-=a[l]; l++; //左缩进 }else if(a[r]&lt;a[l]){ ans+=(c[l]==c[r]?0:a[r]); a[l]-=a[r]; r--; //右缩进 }else{ //a[l]==a[r] ans+=(c[l]==c[r]?0:a[r]); l++;r--; //左右数量相等时需要同时缩进 } }cout&lt;&lt;ans&lt;&lt;endl; return 0; } </code></pre> <p>三目运算符可扩写为:</p> <pre><code class="language-cpp">if(c[l]!=c[r]){ ans+=a[l]; //或者a[r] } </code></pre> <p>当然,本题的while循环内并不需要直接并列三个 <code>if</code> 语句,而是<del>蒟蒻考场上这么写</del>。</p> <p>这里还有一种做法:</p> <pre><code class="language-cpp">while(l&lt;r){ long long p=min(a[l],a[r]); a[l]-=p;a[r]-=p; ans+=(c[l]==c[r]?0:p); if(a[l]==0) l++; //等于0表示已经判断完,需要缩进 if(a[r]==0) r--; } </code></pre> <p>特别的,明显第二种做法更优。</p> <h2>正确性说明</h2> <p>回文串要求第 $i$ 个字符和第 $L+1−i$ 个字符相同。我们从两端向中间配对。</p> <p>每一对配对的字符,如果相同则无需修改;如果不同,则至少需要修改其中一个。</p> <p>由于每段内字符相同,左右两端各取 $min(a[l], a[r])$ 个字符进行配对,这些配对要么全部相同(即 $c_l=c_r$),要么全部不同(即 $c_l \neq c_r$)。不同的那些对,每对修改一个字符即可,因此贡献为 $min(a[l], a[r])$。</p> <p>消去后继续处理剩余部分,直到所有位置配对完毕。</p> <p>每一步的贡献都是下界,且可以同时达到,所以贪心最优。</p> <h2>时间复杂度</h2> <p>由于每个段只会被遍历 $1$ 次,且 $l$ 只增,$r$ 只减,因此时间复杂度为 $O(n)$。</p> <p>需要存储 $a_i$ 与 $c_i$ 数组,因此空间复杂度为 $O(n)$。</p> <p><a href="https://www.luogu.com.cn/record/307152462">AC记录</a></p>
评论 (0)

暂无评论,来抢沙发。

登录后即可发表评论。
返回专栏