2022/4/19 天梯赛刷题记录

本文介绍了两个算法问题:L2-006树的遍历和L2-008最长对称子串。树的遍历中,通过递归构建并输出二叉树的中序遍历序列;最长对称子串问题,通过双指针检查字符串的对称性,找到最长对称子串的长度。这些题目考察了数据结构和字符串处理的基本技能。

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

天梯赛的题面是越来越难读懂,读题真费劲

L2-006 树的遍历

#include <bits/stdc++.h>
using namespace std;
#define endl '\n';
typedef long long ll;
typedef pair<int,string> PII;
const int  N=1e5+10,mod=1e9+7;
int n,in[N],pre[N],pos[N];
void build(int l1,int r1,int l2,int r2,int idx){
    if(l1>r1||l2>r2) return ;
    int l=l1;
    while(in[l]!=pre[r2]) l++;
    pos[idx]=in[l];
    build(l1,l-1,l2,l2+l-1-l1,2*idx+1);
    build(l+1,r1,l2+l-l1,r2-1,2*idx+2);
}
int main() {
	cin>>n;
    for(int i=0;i<n;i++) cin>>pre[i];
    for(int i=0;i<n;i++) cin>>in[i];
    build(0,n-1,0,n-1,0);
    int cnt=0;
    for(int i=0;i<100000;i++){
        if(cnt==n) break;
        if(pos[i]){
            cnt++;
            if(i) cout<<" ";
            cout<<pos[i];
        }
    }
	return 0;
}

L2-008 最长对称子串

#include <bits/stdc++.h>
using namespace std;
#define endl '\n';
typedef long long ll;
typedef pair<int,string> PII;
const int  N=1e5+10,mod=1e9+7;
string s;
bool check(int l,int r) {
    while(l<r){
        if(s[l++]!=s[r--]) return false;
    }
    return true;
}
int main() {
	getline(cin,s);
    int n=s.size()-1;
    int ans=0;
    for(int i=0;i<=n;i++){
        for(int j=n;j>=i;j--){
            if(check(i,j)) {
                ans=max(ans,j-i+1);
                break;
            }
        }
    }
    cout<<ans<<endl;
	return 0;
}

L2-030 冰岛人

#include <bits/stdc++.h>
using namespace std;
#define endl '\n';
typedef long long ll;
typedef pair<int,string> PII;
int N, M;
string fName, sName, temp;
map<string, PII> mp;
string check(string a, string b) {
	int cnt1 = 0, cnt2;
	while (a != "") {
		cnt2 = 0;
		string b2 = b;
		while (b2 != "") {
			if (a == b2 && (cnt1 < 4 || cnt2 < 4)) return "No\n";
			if (cnt1 >= 4 && cnt2 >= 4) return "Yes\n";
			b2 = mp[b2].second;
			cnt2++;
		}
		a = mp[a].second;
		cnt1++;
	}
	return "Yes\n";
}
int main() {
	cin >> N;
	while(N--){
		cin >> fName >> sName;
		if (sName.back() == 'n') mp[fName] = {1, sName.substr(0, sName.length() - 4)};
		else if (sName.back() == 'r') mp[fName] = {0, sName.substr(0, sName.length() - 7)};
		else if (sName.back() == 'm') mp[fName].first = 1;
		else mp[fName].first = 0;
	}
	cin >> M;
	while(M--){
		cin >> fName >> temp >> sName >> temp;
		if (!mp.count(fName) || !mp.count(sName)) cout << "NA\n";
		else if(mp[fName].first == mp[sName].first) cout << "Whatever\n";
		else cout << check(fName, sName);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懂又不懂啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值