跳到正文

题解

题解:P13677 [GCPC 2023] Loop Invariant

_DXC_约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月12日
篇幅
约 6 分钟
获赞
1
题目
P13677

版本

  1. v1当前

前言

我是蒟蒻,第一次写题解,望通过、夶佬喷轻点

题意简述

由输出格式可以知道,我们需要将:

一个给定的已平衡的括号序列,从一个地方开始,将这个地方的前面的括号移到后面,使其不但平衡,而且与原来的的括号序列不等。

题目分析

前提阐要

我们首先需要知道什么是平衡序列,这一点题目中已给出。

像如下几个例子:

  • ( ) ( ) ( ( ) )
  • ( ( ) ) ( ) ( )
  • ( ( ( ) ) ) ( )
  • ( ( ( ( ) ) ) )
  • ( ) ( ) ( ( ) )
  • ⋅⋅⋅\cdot\cdot\cdot

根据例子,我们知道 其实之前也知道 就是 一个左括号 对应一个 右括号。

根据这个,我们可以统计一下左右括号的数量。 如果数量相等,那么就是平衡的 (一会儿再讲有什么用)。

思路讲解

实际上,这道题真正的意思是看你 从哪个地方开始(设这个地方是 idxidx ),到结束( endend ) 与 从开始( beginbegin )到 idxidx 的两个字符串相加到一起( ansans ),再与原来的字符串( ss )相比较,看看是否相同。

这么说可能比较抽象,给你举个例子:

()()(())
01234567

这个显然是个 平衡序列 ( ) ( ) ( ( ) ) ,它的 begin=0begin = 0 , end=7end = 7 (此定义只在这个题解中)。

而我们的 idx 我们就设它为 1,即:

idx=1idx = 1

由上面我说的,得到 ans=“()(())()”ans = “()(())()” 再比较,发现它与 ss 不一样,所以我们就输出 ansans 即 ( ) ( ( ) ) ( )。

如果相同就输出 no。

正确性证明

《西江月⋅证明》《西江月\cdot证明》

  即得易见平凡,仿照上例显然。留作习题答案略,读者自证不难。   反之亦然同理,推论自然成立,略去过程QED,由上可知证毕。

手动哔声。

  1. ansans 肯定是平衡的,即对于任何切割点 idxidx,将前 idxidx 个字符移到后面后,新序列 ansans 仍然是一个平衡序列。
      • 存在 ansans 的条件:如果原序列不是由同一个子串重复多次构成的(即非周期性的),那么一定存在至少一个切割点 ii 使得 ans≠sans \neq s。
      • 这是因为如果所有切割点生成的 ansans 都等于 ss,那么 ss 必须是由某个子串重复多次构成的(即 ss 是周期性的)。
    1. “no”情况判断:如果原序列是由同一个子串重复多次构成的(即周期性的),那么所有切割点生成的 ansans 都会与原序列 ss 相同,此时应输出 “no”。

代码实现

片段代码解释

C++
#include <iostream>
#include <string>

 using namespace std;

必须头文件

C++
#include <bits/stdc++.h>

using namespace std;

或者万能头文件

C++
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

竞赛必备,解cin、cout与printf、scanf的绑定,加快cin、cout的速度(非常快,但没有快读 模板 快)

C++
	string s, ans = "";
	cin >> s;

	int cnt = 0, id, len = s.size(), t = 0;

初始化并读入

C++
	for(int i = 0; i < len; i++) {
		char c = s[i];

		if(c == '(') cnt++;
		else cnt--;

		if(cnt == 0) {
			id = i;
			break;
		}
	}
	id++;

寻找 idxidx

C++
	for(int i = id,ii = 0; ii < len; i++,ii++){
		i %= len;
		if(s[i] == s[ii])
			t++;
		ans += s[i];
	}

构造 ansans

这里 tt 的作用是判断 ansans 与 ss 的相似度,后面有。

C++
	if(t == len) cout << "no" << endl;
	else cout << ans << endl;

判断 ansans 是否和 ss 完全一样。如果是,则输出no,否则为答案 ansans

C++
	return 0;

必备 去了似乎也没影响?

完整代码

C++
#include <iostream>
#include <string>
//#include <bits/stdc++.h>
using namespace std;

int main() {
//	ios::sync_with_stdio(false);
//	cin.tie(0); cout.tie(0);

	string s, ans = "";
	cin >> s;

	int cnt = 0, id, len = s.size(), t = 0;

	for(int i = 0; i < len; i++) {
		char c = s[i];

		if(c == '(') cnt++;
		else cnt--;

		if(cnt == 0) {
			id = i;
			break;
		}
	}
	id++;
	for(int i = id,ii = 0; ii < len; i++,ii++){
		i %= len;
		if(s[i] == s[ii])
			t++;
		ans += s[i];
	}
	if(t == len) cout << "no" << endl;
	else cout << ans << endl;

	return 0;
}

结语

我是蒟蒻,第一次写题解,望通过、夶佬喷轻点

原文