CodeForces ~ 988B ~ Substrings Sort (水,排序)

本文介绍了一种通过排序和匹配来解决字符串是否可以按特定顺序排列的问题。算法首先按字符串长度进行排序,然后检查每个字符串是否为下一个字符串的子串。若所有字符串都能满足条件,则输出排列方式。

题意:给你N个字符串,问能否将他们重新排列,使得每个串都是后一个串的子串,能输出YES,输出这种排列,不能输出NO。


思路:因为如果有解,那么短的串一定是长的串的子串,所以按字符串长度排序,判断每个串是不是后一个串的子串即可。


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 105;
int n;
string str[MAXN];
int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++) cin >> str[i];
    sort(str, str+n, [](string a, string b){ return a.size() < b.size(); });
    bool flag = true;
    for (int i = 0; i < n-1; i++)
    {
        if (str[i+1].find(str[i]) == string::npos)
        {
            flag = false;
            break;
        }
    }
    if (flag)
    {
        printf("YES\n");
        for (int i = 0; i < n; i++) cout << str[i] << endl;
    }
    else printf("NO\n");
    return 0;
}

### Codeforces Round 988 Div. 3 的题目及题解 #### A. Add to Nearest Integer 在这个问题中,给定一个浮点数 \( x \),目标是将其四舍五入到最接近的整数。如果该数字恰好位于两个整数之间,则应向绝对值更大的方向舍入。 ```cpp #include <iostream> #include <cmath> using namespace std; void solve() { double x; cin >> x; cout << round(x) << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { solve(); } } ``` 此代码通过 `round` 函数实现了对输入浮点数的处理[^1]。 #### B. Array Sharpening 对于这个问题,有一个长度为 \( n \) 的数组 \( a \),需要找到是否存在一对索引 \( i \neq j \),使得 \( |a_i - a_j| \ge k \)[^2]。 ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; bool canBeSharped(vector<int>& nums, int diff) { sort(nums.begin(), nums.end()); for (size_t i = 0; i < nums.size() - nums[i]) >= diff) return true; } return false; } void solve() { int n, k; cin >> n >> k; vector<int> a(n); for (auto& ai : a) cin >> ai; cout << (canBeSharped(a, k) ? "YES" : "NO") << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); size_t tests; cin >> tests; while(tests --> 0) solve(); return 0; } ``` 这段程序首先对接收到的数据进行了排序,接着遍历查找是否有满足条件的一对元素。 #### C. Minimum Grid Path Cost 本题涉及在一个二维网格上的路径规划,其中每一步都有一定的花费。目的是计算从左上角移动至右下角所需的最小费用总和[^3]。 由于未提供具体算法实现细节,在这里仅描述思路而不展示完整的源码片段。通常这类问题可以通过动态规划来解决,维护一个二维表记录到达各位置时累积成本最低的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值