Codeforces Round #629 (Div. 3) C. Ternary XOR(贪心)
A number is ternary if it contains only digits 00 , 11 and 22 . For example, the following numbers are ternary: 10221022 , 1111 , 2121 , 20022002 .
You are given a long ternary number xx . The first (leftmost) digit of xx is guaranteed to be 22 , the other digits of xx can be 00 , 11 or 22 .
Let's define the ternary XOR operation ⊙⊙ of two ternary numbers aa and bb (both of length nn ) as a number c=a⊙bc=a⊙b of length nn , where ci=(ai+bi)%3ci=(ai+bi)%3 (where %% is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by 33 . For example, 10222⊙11021=2121010222⊙11021=21210 .
Your task is to find such ternary numbers aa and bb both of length nn and both without leading zeros that a⊙b=xa⊙b=x and max(a,b)max(a,b) is the minimum possible.
You have to answer tt independent test cases.
The first line of the input contains one integer tt (1≤t≤1041≤t≤104 ) — the number of test cases. Then tt test cases follow. The first line of the test case contains one integer nn (1≤n≤5⋅1041≤n≤5⋅104 ) — the length of xx . The second line of the test case contains ternary number xx consisting of nn digits 0,10,1 or 22 . It is guaranteed that the first digit of xx is 22 . It is guaranteed that the sum of nn over all test cases does not exceed 5⋅1045⋅104 (∑n≤5⋅104∑n≤5⋅104 ).
For each test case, print the answer — two ternary integers aa and bb both of length nn and both without leading zeros such that a⊙b=xa⊙b=x and max(a,b)max(a,b) is the minimum possible. If there are several answers, you can print any.
4 5 22222 5 21211 1 2 9 220222021
11111 11111 11000 10211 1 1 110111011 110111010
题干啰里啰唆一堆==
观察一下样例甚至都能找到贪心策略:因为要尽可能保证大的那个数较小,所以尽可能使两个数接近。设置一个标记big,从原数的最高位往低位遍历,当big没有被赋值时,如果原数这一位是2:新数的这一位都赋为1;如果原数这一位是0:新数的这一位都赋为0;如果原数这一位是1:随便给一个数的这一位赋1,并把big设置为这个数,另一个数赋值为0;只要big标记设置了,以后原数的每一位都给非big标记的数,有big标记的数赋值为0.
emmm还是看代码吧。
#include <bits/stdc++.h> using namespace std; char s[50005],s1[50005],s2[50005]; int n; int main() { int t; cin>>t; while(t--) { cin>>n; scanf("%s",s); s1[0]='1';s2[0]='1'; int i; int big=-1; for(i=1;i<=n-1;i++) { if(big==1)//已经能分出谁大谁小了 { s2[i]=s[i]; s1[i]='0'; } else { if(s[i]=='0') { s1[i]=s2[i]='0'; } else if(s[i]=='1') { s1[i]='1'; s2[i]='0'; big=1; } else if(s[i]=='2') { s1[i]=s2[i]='1'; } } } for(i=0;i<n;i++) { cout<<s1[i]; } cout<<endl; for(i=0;i<n;i++) { cout<<s2[i]; } cout<<endl; } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!