清华大学机试 需要二刷 *贪心算法,比较虎人

Posted songlinxuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了清华大学机试 需要二刷 *贪心算法,比较虎人相关的知识,希望对你有一定的参考价值。

基本思想:

想到贪心,但是觉得时间复杂度太高,结果一不小心写出来个更复杂的贪心;

 

关键点:

注意特殊用例,有可能无法遍历出正确结果,即没有切换得到正确的值,此时要避免进入死循环;

 

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
using namespace std;

const int maxn = 5010;
int n,m;
int dp[maxn][maxn];

vector<string>v1;
vector<string>v2;

int main() {
    while (cin>>n){
        string s;
        for (int i = 0; i < n; i++) {
            cin >> s;
            v1.push_back(s);
        }
        cin >> m;
        for (int i = 0; i < m; i++) {
            cin >> s;
            v2.push_back(s);
        }
        int cnt = 0;
        int index = 0;
        bool flag = true;
        while (index != m&&flag) {
            int mx = 0;
            int mindex = 0;
            int st = index;
            for (int i = 0; i < n; i++) {
                int j = st;
                while (j<m&&v1[i] != v2[j]){
                    j++;
                }
                if (mx < j - index) {
                    mx = j - index;
                    mindex = j;
                }
            }
            if (mindex == 0)
                flag = false;
            cnt++;
            index = mindex;
        }
        if(flag)
            cout << cnt-1 << endl;
        else
            cout << -1 << endl;
    }
    return 0;
}

 

以上是关于清华大学机试 需要二刷 *贪心算法,比较虎人的主要内容,如果未能解决你的问题,请参考以下文章

北京大学机试 I Wanna Go Home 需要二刷 *最短路径衍生问题

北邮机试 矩阵幂计算器 需要二刷 *快速幂问题的扩展

清华大学机试 剩下的树 Easy *贪心的区间思想

20210822-周总结

「模拟8.21」虎

报道清华毕业计算机教授靠“贪心算法”追踪劫匪,秒杀美国警察!