Codeforces Round #739 (Div. 3)

比赛链接

Codeforces Round #739 (Div. 3)

E. Polycarp and String Transformation

Polycarp 有一个给定的字符串 s 和初始为空的字符串 t 。他将会重复以下操作直到字符串 s 为空:

  • t 后面拼接 s ,然后选择一个 s 中的字母并删去 s 当中出现的这个字母。
    例如,如果 s=abacaba ,并执行以下操作。
  • t 后面拼接 s ,然后删去 s 当中所有出现的 b 。在这次操作之后, t=abacabas=aacaa。 
  • t 后面拼接 s ,然后删去 s 当中所有出现的 a。在这次操作之后, t= abacabaaacaa, s=c。 
  • t 后面拼接 s ,然后删去 s 当中所有出现的 c。在这次操作之后, t= abacabaaacaac, s 为空字 符串。
    因此,最终的字符串 t 为 abacabaaacaac。

现在给你操作完之后的字符串 t 。请你回答: 是否存在一个字符串 s 和一个删字母的顺序,使得操作完以后 可以得到字符串 t ? 如果可以,请你求出 s 和删字母的顺序,否则输出 1
T 组数据, 1T1041|t|,|t|5×105

解题思路

思维

很容易找到删除的顺序,即最后一个字符肯定是最后删除的,从后往前推即可找出顺序删除的字符,现在关键在于如何求出原串的长度 len,假设删除的字符的串为 t,其长度为 m,如果满足要求,则一定有:

cnt[t[0]]+cnt[t[1]]++cnt[t[m]]

其中 cnt[i] 表示 i 在原串中出现的次数,不妨先统计每个字符在 s 中出现的总次数为 cnt[i],由于该字符被删后后面都不会出现,记录该字符在 t 中出现的位置pos(下标从 1 开始),即对于该字符来说原串在删除字符的同时循环了 pos 次,则原串中该字符出现的次数为 cnt[i]/pos

  • 时间复杂度:O(26n)

代码

// Problem: E. Polycarp and String Transformation // Contest: Codeforces - Codeforces Round #739 (Div. 3) // URL: https://codeforces.com/contest/1560/problem/E // Memory Limit: 256 MB // Time Limit: 3000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } int t,cnt[26]; string s; string ck(string s,string t) { for(char c:t) if(s.find(c)==-1)return "-1"; string res=s; for(char c:t) { s.erase(remove(s.begin(),s.end(),c),s.end()); res+=s; } return res; } int main() { help; for(cin>>t;t;t--) { cin>>s; int n=s.size(); string t; for(int i=n-1;i>=0;i--) if(t.find(s[i])==-1)t=s[i]+t; memset(cnt,0,sizeof cnt); for(char c:s)cnt[c-'a']++; int len=0; for(char c:t) { int tt=t.find(c)+1; cnt[c-'a']/=tt; len+=cnt[c-'a']; } string res=s.substr(0,len); if(ck(res,t)==s)cout<<res<<' '<<t<<'\n'; else puts("-1"); } return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/16303960.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示