目录
1.牛牛的快递
2. 最小花费爬楼梯
3.数组中两个字符串的最小距离
1.牛牛的快递
链接
单纯分类讨论,不加赘述。
详细代码:
#include <iostream>
using namespace std;
#define ll long long
int main() {
float mg;
char st;
cin >> mg >> st;
if(mg == 0.0)
{
cout << 0 << endl;
}
else if(mg <= 1.0)
{
if(st == 'y')
cout << 25 << endl;
else
cout << 20 << endl;
}
else
{
ll newm = mg - 1 + 0.9;
if(st == 'y')
printf("%lld\n", 25 + newm);
else
printf("%lld\n", 20 + newm);
}
}
2. 最小花费爬楼梯
链接
看题目就清楚了,一眼dp(动态规划)。
dp三步走:
1.分析几维(当然也能直接创建多个数组分开分析)
2.初始化dp表
3.动态填表
注意:该题的目的地是下表位n的位置,而不是n-1。
#include <iostream>
#include <vector>
using namespace std;const int N = 1e5 + 10;int dp[N][2];int main() {int n;cin >> n;vector<int> cost(N);for(int i = 0; i < n; ++i){cin >> cost[i];}// 从下标0开始dp[0][0] = 0;dp[1][0] = cost[0];// 从下标1开始dp[1][1] = 0;dp[2][1] = cost[1];// 状态转移方程for(int i = 2; i <= n; ++i){dp[i][0] = min(dp[i - 1][0] + cost[i - 1], dp[i - 2][0] + cost[i - 2]);}for(int i = 3; i <= n; ++i){dp[i][1] = min(dp[i - 1][1] + cost[i - 1], dp[i - 2][1] + cost[i - 2]);}cout << min(dp[n][0], dp[n][1]) << endl;return 0;
}
3.数组中两个字符串的最小距离
我当时的想法非常单一,就是想着用两个数组将s1和s2在vector<string>中的位置储存起来,然后遍历两个数组,求其相减的最小值,可能由于n只到了1e5,就全案例通过了。
1.自己思路(能跑过)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define int long long
const int N = 1e5 + 10;
signed main() {int n;cin >> n;string s1;string s2;cin >> s1 >> s2;int c1[N];int c2[N];vector<string> vs(N);for (int i = 0; i < n; ++i){cin >> vs[i];}int j = 0, k = 0;if (n < 2){cout << -1 << endl;return 0;}else{for (int i = 0; i < n; ++i){if (vs[i] == s1)c1[j++] = i;if (vs[i] == s2)c2[k++] = i;}}if (j == 0 || k == 0){cout << -1 << endl;return 0;}int mi = 0x3f3f3f3f;for (int i = 0; i < j; ++i){for (int l = 0; l < k; ++l){mi = min(mi, abs(c2[l] - c1[i]));}}cout << mi << endl;return 0;
}
2.优化(预处理思想 这里也可以看做dp吧)
时间复杂度O(N):
#include <vector>
#include <algorithm>
using namespace std;
#define int long long
const int N = 1e5 + 10;
signed main() {int n;cin >> n;string s1;string s2;cin >> s1 >> s2;int a[N];vector<string> vs(N);for (int i = 0; i < n; ++i){cin >> vs[i];}int prev1 = -1;int prev2 = -1;int ret = 0x3f3f3f3f;for (int i = 0; i < n; ++i){if (vs[i] == s1){if (prev2 != -1){ret = min(ret, i - prev2);}prev1 = i;}else if(vs[i] == s2){if (prev1 != -1){ret = min(ret, i - prev1);}prev2 = i;}}if (ret == 0x3f3f3f3f)cout << -1 << endl;elsecout << ret << endl;return 0;
}