惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
GbyAI
GbyAI
S
SegmentFault 最新的问题
量子位
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
IT之家
IT之家
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
雷峰网
雷峰网

博客园 - 谢绝围观

LeetCode 910. Smallest Range II EAC 抓取CD为AAC文件 Binary Indexed Tree (Fenwick Tree) LintCode 896. Prime Product 简明题解 UVa 1471 - Defense Lines Windows下安装配置MinGW GCC调试环境 详解LeetCode 137. Single Number II LeetCode 309. Best Time to Buy and Sell Stock with Cooldown LeetCode 84. Largest Rectangle in Histogram 修改注册表删除Windows资源管理器 “通过QQ发送” 右键菜单项 LeetCode 312. Burst Balloons LeetCode 287. Find the Duplicate Number LeetCode 10. Regular Expression Matching LeetCode 117. Populating Next Right Pointers in Each Node II 在Windows Azure VM下搭建SSTP VPN - 谢绝围观 利用.NET Code Contracts实现运行时验证 Log4net 配置实例 解决Windows Server 2012 下利用RRAS创建VPN断线的问题 - 谢绝围观 慎用静态类static class
Lint Code 1365. Minimum Cycle Section
谢绝围观 · 2018-04-30 · via 博客园 - 谢绝围观

这题可以看作POJ 1961 最小循环节的一个简化版本。某补习班广告贴里给出的两个指针的参考解法简直大误。

受POJ 1961的启发,把数组看作字串,观察可知,如果字串全部由循环节构成(包括最后一段是不完整循环节的情况),则字串刨去最后一个字符的最长匹配前缀为最小循环节。而“最后一个字符的最长匹配前缀”即为KPM里的pattern[length -1]。所以我们只需按标准KMP算法求一遍失配函数即可。

    int minimumCycleSection(vector<int> &a) {
        size_t len = a.size();
        if(len <= 1) return len;
        int pattern[len];
        memset(pattern, 0, len * 4);
        pattern[0] = -1;
        for(size_t i = 1; i < len; i++){
            int j = pattern[i-1]+1;
            while(a[i] != a[j] && j > 0){
                j = pattern[j-1] + 1;
            }
            pattern[i] = a[i] == a[j] ? j : -1;
        }
        return len - pattern[len-1] - 1;
    }