Codeforces Global Round 4 - 1178E. Archaeology(鸽巢原理)

本文提供了一种解决Codeforces竞赛中E题的有效方法。通过分析题目要求,利用贪心算法从字符串两端寻找相等字符,形成回文子序列。代码实现简洁高效,展示了算法设计与实现的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://codeforces.com/contest/1178/problem/E

题意:给出一个只包含 a,b,c 的字符串 s ,保证任意两个连续的字符都不相同,要求选出一个子序列 t 使得它是一个回文串,并且|t|\geq \left \lfloor \frac{|s|}{2} \right \rfloor

思路:贪心从两端取,因为任意两个连续的字符都不相同,再根据抽屉原理,左端的两个字符和右端的两个字符,必然会有两个相等,所以我们两个两个找即可。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ul;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define mp make_pair
#define pb push_back
#define all(x) x.begin(), x.end()
#define bug prllf("*********\n")
#define debug(x) cerr<<#x<<" = "<<(x)<<endl
#define debugp(x) cerr<<#x<<"= {"<<(x.first)<<", "<<(x.second)<<"}"<<endl
#define debug2(x, y) cerr<<"{"<<#x<<", "<<#y<<"} = {"<<(x)<<", "<<(y)<<"}"<<endl
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const int mod = 998244353;
const double eps = 1e-8;
const double pi = acos(-1);
const int N = 1e6 + 7;
string s;
int vis[N];
int main()
{
    IO; cin >> s;
    int l = 0, r = s.length() - 1;
    while(l <= r)
    {
        if(l == r) {vis[l] = 1; break;}
        if(s[l] == s[r]) vis[l] = vis[r] = 1;
        else if(s[l] == s[r-1]) vis[l] = vis[r-1] = 1;
        else if(s[l+1] == s[r]) vis[l+1] = vis[r] = 1;
        else if(s[l+1] == s[r-1]) vis[l+1] = vis[r-1] = 1;
        l += 2, r -= 2;
    }
    for(int i = 0; i < s.length(); i++)
        if(vis[i]) cout << s[i];
    cout << '\n';
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值