练习cf1400A. String Similarity

题目如下
A. String Similarity
time limit per test2 seconds
memory limit per test256 megabytes
A binary string is a string where each character is either 0 or 1. Two binary strings 𝑎 and 𝑏 of equal length are similar, if they have the same character in some position (there exists an integer 𝑖 such that 𝑎𝑖=𝑏𝑖). For example:

10010 and 01111 are similar (they have the same character in position 4);
10010 and 11111 are similar;
111 and 111 are similar;
0110 and 1001 are not similar.
You are given an integer 𝑛 and a binary string 𝑠 consisting of 2𝑛−1 characters. Let's denote 𝑠[𝑙..𝑟] as the contiguous substring of 𝑠 starting with 𝑙-th character and ending with 𝑟-th character (in other words, 𝑠[𝑙..𝑟]=𝑠𝑙𝑠𝑙+1𝑠𝑙+2…𝑠𝑟).

You have to construct a binary string 𝑤 of length 𝑛 which is similar to all of the following strings: 𝑠[1..𝑛], 𝑠[2..𝑛+1], 𝑠[3..𝑛+2], ..., 𝑠[𝑛..2𝑛−1].

Input
The first line contains a single integer 𝑡 (1≤𝑡≤1000) — the number of test cases.

The first line of each test case contains a single integer 𝑛 (1≤𝑛≤50).

The second line of each test case contains the binary string 𝑠 of length 2𝑛−1. Each character 𝑠𝑖 is either 0 or 1.

Output
For each test case, print the corresponding binary string 𝑤 of length 𝑛. If there are multiple such strings — print any of them. It can be shown that at least one string 𝑤 meeting the constraints always exists.

题目大意
现规定两个串中若存在某一位置的元素相同就称为相似。
有这样一个长度为2n-1的串,现在要找出与𝑠[1..𝑛], 𝑠[2..𝑛+1], 𝑠[3..𝑛+2], ..., 𝑠[𝑛..2𝑛−1],都相似 的一个串。

题目分析
要构造一个串w,使得w和每个窗口至少有一个元素重合才称之为相似。那么,w[i] 要等于某个窗口中第j个位置的字符,w和第j个窗口s[j..j+n-1]的第j位相等,那么保证了每个窗口至少有一位重合。

点击查看代码
#include <iostream>
#include <string>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        string s;
        cin >> s;
        string w;
        for(int i = 0; i < n; i++){
            w += s[i * 2];
        }
        cout << w << endl;
    }
    return 0;
}
posted @ 2025-07-22 22:14  sirro1uta  阅读(7)  评论(0)    收藏  举报