[acwing周赛复盘] 第 92 场周赛20230225 补

本文是关于AcWing编程竞赛第92场周赛的复盘,重点讨论了三道题目:4864.多边形、4865.有效类型和4866.最大数量。4864题太简单未详细展开,4865题通过栈模拟和先根遍历两种方法解决,4866题采用并查集策略求解最大数量。文章提供了代码实现和思路分析。
摘要由CSDN通过智能技术生成

一、本周周赛总结

  • 有事去工地没打。第二天补的,这场好难啊。
  • T1 模拟。
  • T2 栈/先根遍历模拟构造。
  • T3 并查集。

二、 4864. 多边形

链接: 4864. 多边形

1. 题目描述

太简单跳过。

三、4865. 有效类型

链接: 4865. 有效类型

1. 题目描述

在这里插入图片描述

2. 思路分析

本题两种做法,都写一下。
  • 表达式的题先想到栈。
  • 一个比较直观的做法是用栈模拟,检查栈顶三个值,满足:s[-3]==pair 且 s[-2]完整合法串 且 s[-1]是合法串完整合法串,则将栈顶这三个值合并成一个合法串。那么最后只要栈只剩一个元素就是最终合法结果。代码参见solve_tle()。
  • 提交后TLE了。想想也是,字符串一直在移动,复杂度是结果长度的平方。

  • 考虑这种做法的优化,其实没必要在合并的路上拼接,只需要记录每个单词中间添加的字符即可,最后拼起来。
  • 观察结果对于原单词数组,每个单词右边都添加几个字符,那么构造一个ans数组,ans[i]代表第i个单词右边添加的字符们。
  • 栈改为储存tuple(0/1,l,r),代表这个串是否合法、组合左边界单词下标、右边界单词下标。
  • 那么显然遇到合法栈顶三个元素,s[-3]后要添加’<‘,s[-2]后要添加’,‘,s[-1]后添加’>'。参见solve1()
  • 这里观察到只储存右边界即可,因此栈可以只存二元组。参见solve2().

  • y总讲了可以先根遍历,我立马暂停视频去写代码了。写完过了,但是果然不如y总优雅。参考solve()
  • 另外,acw的py设置递归深度会segment fault,惊呆了。只好改成@bootstrap写法。

3. 代码实现

# Problem: 有效类型
# Contest: AcWing
# URL: https://www.acwing.com/problem/content/4868/
# Memory Limit: 256 MB
# Time Limit: 1000 ms

import sys
import bisect
import random
import io, os
from bisect import *
from collections import *
from contextlib import redirect_stdout
from itertools import *
from array import *
from functools import lru_cache
from types import GeneratorType
from heapq import *
from math import sqrt, gcd, inf

if sys.version >= '3.8':  # ACW没有comb
    from math import comb

RI = lambda: map(int, sys.stdin.buffer.readline().split())
RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())
RILST = lambda: list(RI())
DEBUG = lambda *x: sys.stderr.write(f'{str(x)}\n')

MOD = 10 ** 9 + 7


#       ms
def solve_tle():
    n, = RI()
    words = list(RS())
    if words == ['int']:
        return print('int')
    p = words.count('pair')
    it = words.count('int')
    if p + 1 != it or words[0] != 'pair' or words[-1] != 'int':
        return print('Error occurred')
    s = []
    for w in words:
        s.append([0, w])
        if w == 'int':
            s[-1][0] = 1
        if len(s) < 3:
            continue
        while len(s) >= 3 and s[-1][0] and s[-2][0] and s[-3][1] == 'pair':
            _, y = s.pop()
            _, x = s.pop()
            s[-1] = [1, f'pair<{x},{y}>']

    if len(s) == 1:
        return print(s[0][1])
    print('Error occurred')


#       ms
def solve1():
    n, = RI()
    words = list(RS())
    if words == ['int']:
        return print('int')
    p = words.count('pair')
    it = words.count('int')
    if p + 1 != it or words[0] != 'pair' or words[-1] != 'int':
        return print('Error occurred')
    s = []
    ans = [''] * len(words)
    for i, w in enumerate(words):
        s.append([0, i, i])
        if w == 'int':
            s[-1][0] = 1

        while len(s) >= 3 and s[-1][0] and s[-2][0] and s[-3][1] == s[-3][2] and words[s[-3][1]] == 'pair':
            _, _, y = s.pop()
            _, _, x = s.pop()
            ans[s[-1][1]] += '<'
            ans[y] += '>'
            ans[x] += ','
            s[-1] = [1, s[-1][1], y]

    if len(s) == 1:
        p = []
        for x, y in zip(words, ans):
            p.append(x)
            p.append(y)

        return print(''.join(p))
    print('Error occurred')

#       ms
def solve2():
    n, = RI()
    words = list(RS())
    if words == ['int']:
        return print('int')
    p = words.count('pair')
    it = words.count('int')
    if p + 1 != it or words[0] != 'pair' or words[-1] != 'int':
        return print('Error occurred')
    s = []
    ans = [''] * len(words)
    for i, w in enumerate(words):
        s.append([0,  i])
        if w == 'int':
            s[-1][0] = 1

        while len(s) >= 3 and s[-1][0] and s[-2][0] and s[-3][0] == 0:
            _,  y = s.pop()
            _,  x = s.pop()
            ans[s[-1][1]] += '<'
            ans[y] += '>'
            ans[x] += ','
            s[-1] = [1,  y]

    if len(s) == 1:
        p = []
        for x, y in zip(words, ans):
            p.append(x)
            p.append(y)

        return print(''.join(p))
    print('Error occurred')


def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc


#       ms
def solve():
    n, = RI()
    words = list(RS())
    n = len(words)
    i = 0
    ans = []
    flag = True  # 这是由于bootstrap做法不能提前return 要用flag去分支

    @bootstrap
    def dfs():
        nonlocal i, flag
        if i >= n:
            i += 1
            flag = False

        if flag:
            o = words[i]
            i += 1
            if o == 'int':
                ans.append('int')
            else:
                ans.append('pair<')
                yield dfs()
                ans.append(',')
                yield dfs()
                ans.append('>')
        yield

    dfs()
    if i != n:
        return print('Error occurred')
    print(''.join(ans))

if __name__ == '__main__':
    solve()

四、4866. 最大数量

链接: 4866. 最大数量

1. 题目描述

在这里插入图片描述

2. 思路分析

并查集。

  • 连边问题优先考虑并查集。
  • 加边时,如果发现顶点x,y本身就是一个家族,那么可以省下一条边从外边家族连一条线进来组成更大家族。
  • 考虑一个有s个顶点的家族,最大的度就是s-1,因为可以所有s-1个点都连同一个点。
  • 因此可以按顺序加边,如果失败(本身是一个家族),记录省下的边数no_use。然后给所有家族size排序,选最大的另外no_use个连向最大家族即可。即求和最大的no_use+1个家族的size。那么只需要把所有家族size列出来排序即可。
  • 注意选家族时技巧是判断i==find_father(i)。
  • 总复杂度是O(d * n * logn)。但由于后边随着边增多,家族数会变小,排序可能用不满nlogn,但是遍历家族起码有个n。
  • 可以从数据量看出来这个复杂度是合理的,如果只要n方,那么可能数据量是3000而不是1000。忽略并查集的最坏情况的log。

  • 另外这里维护最大的k个家族size,考虑可以用懒删除大顶堆优化:
    • 维护堆里的家族size,和一个已移除数据的Counter()。
    • 当合并时,对cnt中添加要移除的两个size数字,并对堆中增加新的size数字。
    • 查询最大k个数时,从堆中有效pop k次,如果这个数cnt[x]>0,则无效,重新pop,同时cnt[x]-1。
    • 这些合法数还得再重新入堆。贼麻烦,常数上可能还不如sort,尤其是python。
  • 用SortedList优化其实是个更好的主意,只需要两次remove和一个add。查询只需要sum([-k:])
  • 他们可以省去遍历家族的n,用log代替排序的nlgn,但sum无法省去。
  • 复杂度优化成d*d,即遍历d次,sum最多d-1个家族。

3. 代码实现

# Problem: 最大数量
# Contest: AcWing
# URL: https://www.acwing.com/problem/content/description/4869/
# Memory Limit: 256 MB
# Time Limit: 1000 ms

import sys
import bisect
import random
import io, os
from bisect import *
from collections import *
from contextlib import redirect_stdout
from itertools import *
from array import *
from functools import lru_cache
from types import GeneratorType
from heapq import *
from math import sqrt, gcd, inf

if sys.version >= '3.8':  # ACW没有comb
    from math import comb

RI = lambda: map(int, sys.stdin.buffer.readline().split())
RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())
RILST = lambda: list(RI())
DEBUG = lambda *x: sys.stderr.write(f'{str(x)}\n')

MOD = 10 ** 9 + 7


class DSU:
    def __init__(self, n):
        self.fathers = list(range(n))
        self.size = [1] * n  # 本家族size
        self.edge_size = [0] * n  # 本家族边数(带自环/重边)
        self.n = n
        self.setCount = n  # 共几个家族

    def find_fa(self, x):
        fs = self.fathers
        t = x
        while fs[x] != x:
            x = fs[x]
        while t != x:
            fs[t], t = x, fs[t]
        return x

    def union(self, x: int, y: int) -> bool:
        x = self.find_fa(x)
        y = self.find_fa(y)

        if x == y:
            self.edge_size[y] += 1
            return False
        if self.size[x] > self.size[y]:
            x, y = y, x
        self.fathers[x] = y
        self.size[y] += self.size[x]
        self.edge_size[y] += 1 + self.edge_size[x]
        self.setCount -= 1
        return True

#       ms
def solve():
    n, d = RI()
    dsu = DSU(n + 1)
    ans = []
    no_use = 0
    for i in range(1, d + 1):
        x, y = RI()
        if not dsu.union(x, y):
            no_use += 1
        s = [dsu.size[j] for j in range(1, n + 1) if j == dsu.find_fa(j)]
        s.sort(reverse=True)
        z = sum(s[:no_use + 1])

        ans.append(z - 1)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()

六、参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值