CF1178E Archaeology

CF1178E Archaeology

思路

根据相邻两个字符不同与鸽巢原理可证明:从前面拿相邻 \(2\) 个与从后面拿 \(2\) 个字符,前后一定会有重复的字符。

所以就通过这个原理构造,这样就能保证每 \(4\) 个字符就有 \(2\) 个字符被选中,正好满足题目说的每 \(2\) 个字符选 \(1\) 个字符。若 \(n\) 不为 \(4\) 的倍数,说明使用上面的方法还会少算中间的 \(1\)~\(3\) 个字符,那就选取其中随意一个字符当中间字符。

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
	ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    string s;
    cin>>s;
    string ans1,ans2;
    int i;
    if(s.size()<=3){
    	cout<<s[0];
    	return 0;
	}
	else if(s.size()==4){
		char s1=s[0],s2=s[1],t1=s[2],t2=s[3];
    	if(s1==t1)cout<<s1<<t1;
    	else if(s1==t2)cout<<s1<<t2;
    	else if(s2==t1)cout<<s2<<t1;
    	else cout<<s2<<t2;
    	return 0;
	} 
    for(i=0;;i+=2){
    	if(i>=s.size()-i-3)break;
    	char s1=s[i],s2=s[i+1],t1=s[s.size()-i-1],t2=s[s.size()-i-2];
    	if(s1==t1)ans1+=s1,ans2+=t1;
    	else if(s1==t2)ans1+=s1,ans2+=t2;
    	else if(s2==t1)ans1+=s2,ans2+=t1;
    	else ans1+=s2,ans2+=t2;
	}
	reverse(ans2.begin(),ans2.end());
	if(s.size()%4==0)cout<<ans1<<ans2;
	else cout<<ans1<<s[i]<<ans2;
	return 0;
}



posted @ 2026-11-07 16:59  halewu  阅读(3)  评论(0)    收藏  举报