清华大学机试 需要二刷 *贪心算法,比较虎人
作者:互联网
基本思想:
想到贪心,但是觉得时间复杂度太高,结果一不小心写出来个更复杂的贪心;
关键点:
注意特殊用例,有可能无法遍历出正确结果,即没有切换得到正确的值,此时要避免进入死循环;
#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; }
标签:index,int,cin,while,二刷,虎人,maxn,机试,include 来源: https://www.cnblogs.com/songlinxuan/p/12386391.html