2020-09-30 刷题记录

701. 二叉搜索树中的插入操作

思路:

\(dfs\)

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
public:
    
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(!root) root = new TreeNode(val);
        else if(val < root->val) root->left = insertIntoBST(root->left, val);
        else root->right = insertIntoBST(root->right, val);
        return root;
    }
};

Cow and Message

原题链接: CodeForces - 1307C

思路:

首先可以确定的是隐藏的字符串的长度一定不超过 \(2\)(因为如果存在比 \(2\) 还长的话,那么其中就可以得到长度为 \(2\) 的隐藏字符串)。

根据上述的结论,设 \(cnt[i][j]\):在 \(s_1\)\(s_i\) 中,字符 \(j\) 出现的个数。

同时记录出每个字符出现的位置。

我们枚举长度为 \(2\) 的字符串可能出现的情况,然后计算出对应的结果。

最后再和长度为 \(1\) 的比较即可。

代码:

const int N = 1e5 + 10;

char s[N];
ll cnt[N][26];
vector<int> rec[26];

int main() {
    
    scanf("%s", s + 1);
    int n = strlen(s + 1);
    memset(cnt, 0, sizeof cnt);
    for(int i = 1; i <= n; i ++) {
        for(int j = 0; j < 26; j ++) cnt[i][j] = cnt[i - 1][j];
        cnt[i][s[i] - 'a'] ++;
        rec[s[i] - 'a'].pb(i);
    }
    ll ans = 0;
    for(int i = 0; i < 26; i ++) {
        for(int j = 0; j < 26; j ++) {  // 枚举字符串 ji 的情况。
            ll tmp = 0;
            for(auto it : rec[i]) {
                tmp += cnt[it - 1][j]; // 该位置下的字符 i 前面有多少个字符 j。
            }
            ans = max(ans, tmp);
        }
    }
    for(int i = 0; i < 26; i ++) ans = max(ans, cnt[n][i]);
    cout << ans << endl;
    return 0;
}
posted @ 2020-09-30 23:24  nonameless  阅读(99)  评论(0编辑  收藏  举报