https://codeforces.com/contest/1833/problem/A
时间: 2023-06-21 20:08:30 浏览: 205
这是一道 Codeforces 竞赛中的题目,题目链接为 https://codeforces.com/contest/1833/problem/A 。
题目大意为给定一个字符串 $s$,要求找到一个最短的回文串 $t$,满足 $t$ 是 $s$ 的子串。如果有多个解,输出任意一个即可。
解题思路:
我们可以先判断 $s$ 自身是否是一个回文串,如果是,直接输出 $s$ 即可。如果不是,我们可以从左往右遍历 $s$,找到第一个出现在 $s$ 中的字符 $c$,并将 $c$ 插入到 $s$ 的最左边,得到一个新的字符串 $t$。此时,$t$ 必定是 $s$ 的子串,并且 $t$ 的长度比 $s$ 的长度多 $1$。我们可以继续检查 $t$ 是否是一个回文串,如果是,输出 $t$,否则重复刚才的操作,直到找到一个回文串为止。
代码实现:
相关问题
https://codeforces.com/contest/1810/problem/Bhttps://codeforces.com/contest/1810/problem/B
Problem:
You are given an array a of n integers. You can perform the following operation any number of times: choose two distinct indices i and j (1≤i,j≤n) such that ai≠aj and replace ai with aj and aj with ai.
An array is called beautiful if it is sorted in non-decreasing order (a1≤a2≤…≤an).
Find the minimum number of operations needed to make the given array beautiful.
Solution:
Observation: If we can't make the array beautiful, output -1.
Let's assume we have a beautiful array as b.
If we swap two distinct indices i and j in array a, then b will also have swapped elements b[i] and b[j]. So, we need to find the minimum number of swaps required to convert array a to array b.
We can do this by counting the number of inversions in array a. An inversion is a pair of indices (i,j) such that i<j and ai>aj. The number of inversions in array a is equal to the number of swaps required to sort the array in non-decreasing order.
If the number of inversions is odd, we can't make the array beautiful.
If the number of inversions is even, then we can make the array beautiful. The minimum number of swaps required is equal to the number of inversions.
Time Complexity: O(n log n)
Space Complexity: O(n)
Implementation:
- First, we count the number of inversions in array a using merge sort.
- If the number of inversions is odd, output -1.
- Otherwise, output the number of inversions.
https://codeforces.com/contest/1808/problem/C
Solution:
Observations:
- If we put a 1 at a particular position, we can't put 1's at positions adjacent to it.
- If there are 'x' 1's in the grid, they must be placed in a way that every 2 1's must have at least 1 0 between them. Otherwise, we can't make the required number of moves.
- If we have a grid of size n x n, then we need at least (n+1)/2 1's to make the required moves.
Approach:
- We can fill the grid diagonally with 1's until we reach the last diagonal that has only one cell.
- If the number of 1's filled is less than (n+1)/2, then we fill in the remaining cells with 0's.
- If the number of 1's filled is greater than (n+1)/2, then we remove the excess 1's starting from the last diagonal.
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Let's see the implementation.
阅读全文