腾讯笔试 第五题 动态规划 成功通过
腾讯笔试
第五题 小Q 休息 工作 健身 问题 全部通过 动态规划
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <stack> using namespace std; int dp[3][100000] = { 100000 }; int work[100000]; int keep[100000]; //greater<int>() int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> work[i]; } for (int i = 0; i < n; i++) { cin >> keep[i]; } //第一天如果休息,休息天数为1 dp[0][0] = 1; //如果可以工作,休息天数为0 if (work[0] == 1) dp[1][0] = 0; //如果可以健身,休息天数为0 if (keep[0] == 1) dp[2][0] = 0; for (int i = 1; i < n; i++) { if (work[i] == 1) { if (keep[i - 1] == 1) //dp[1][i] = min(前一天休息,前一天健身); dp[1][i] = min(dp[0][i - 1], dp[2][i - 1]); else dp[1][i] = dp[0][i - 1]; } else dp[1][i] = n; if (keep[i] == 1) { if (work[i - 1] == 1) //dp[2][i] = min(前一天休息,前一天工作); dp[2][i] = min(dp[0][i - 1], dp[1][i - 1]); else dp[2][i] = dp[0][i - 1]; } else dp[2][i] = n; //dp[0][i] = min(前一天工作,前一天健身,前一天休息); int min_num= dp[0][i - 1]; if (work[i - 1] == 1) { min_num = min(dp[1][i - 1], min_num); } if (keep[i - 1]==1) { min_num = min(dp[2][i - 1], min_num); } dp[0][i] = min_num + 1; } int goal = min(dp[0][n-1], dp[1][n-1]); goal = min(dp[2][n-1], goal); cout << goal; }
第四题通过 30%
//第四题 #include <iostream> #include <algorithm> #include <vector> #include <string> #include <stack> using namespace std; int look_left(vector<int> num, int p) { int _this=0; int max; if (p == 0) { return 0; } _this++; p--; max = num[p]; while (1) { if (p == 0) { break; } if (num[p - 1] > max) { _this++; max = num[p - 1]; } p--; } return _this; } int look_right(vector<int> num, int p,int n) { int _this = 0; int max; if (p == n-1) { return 0; } _this++; p++; max = num[p]; while (1) { if (p == n-1) { break; } if (num[p + 1] > max) { _this++; max = num[p + 1]; } p++; } return _this; } //greater<int>() int main() { vector<int> num; vector<int> left; vector<int> right; vector<int> goal; int n; cin >> n; for (int i = 0; i < n; i++) { int mid; cin >> mid; num.push_back(mid); } for (int i = 0; i < n; i++) { cout << look_left(num, i)+ look_right(num, i, n)+1 <<" "; } }
第一第二第三都是40 40 40 这就是命吧