1、题目
1,ceil向上取等
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float a;
char b ;
int ret = 0;
cin>>a>>b;
if(a<=1)
{
ret+=20;
}
else
{
ret+=20;
a-=1;
ret+=ceil(a);//ceil向上取整
}
if(b=='y') ret+=5;
cout<<ret<<endl;
return 0;
}
不用ceil
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float a;
char b;
int ret = 0;
cin>>a>>b;
if(a<=1)
{
ret +=20;
}
else {
ret+=20;
a-=1;
if(a-(int)a>0) ret=ret+a+1;
else ret+=a;
}
if(b=='y')
ret+=5;
cout<<ret<<endl;
}
本道题判断逻辑想的不是很清楚,不熟悉ceil向上取整函数。
2、题目
算法原理:
动态规划
红色1代表到达i位置的第一种可能,红色2代表到达i位置的第2种可能.
1.状态表示
dp[i]表示:到达i位置时的最小花费
2.状态转移方程
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[1-2]);
//解释dp[i-1]+cost[i-1]代表到达i-1的花费和i-1位置的花费, dp[i-2]+cost[1-2]代表到达i-2的花费和i-2位置的花费。
#include <iostream>
using namespace std;
const int N = 1e5+10;
int n ;
long long cost[N];
long long dp[N];
int main() {
cin>>n;
for (int i = 0; i<n; i++) {
cin>>cost[i];
}
dp[0] = 0;
dp[1] = 0;
for(int i = 2;i <= n;i++)
{
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
}
cout<<dp[n]<<endl;
return 0;
}
// 64 位输出请用 printf("%lld")
动态规划不熟悉。
3、题目
题意:
给你两个数组,找到包含这两个数组的最短距离
解法一:暴力解法会超时
解法二:贪心(dp)
eg:
前驱:目标位置往前到另一个目标位置的下标。
prev1:QWER向左前驱找到目标666的下标
prev2:666向左前驱找到目标QWER的下标
ret:最短距离。
#include <iostream>
#include<string>
using namespace std;
int main() {
int n;
string str1,str2,str;
cin>>n;
cin>>str1>>str2;
int prev1 = -1,prev2 =-1;
int ret = 0x3f3f3f3f;//(不存在)
for(int i = 0;i<n;i++)
{
cin>>str;
if(str==str1)//去前面找str2
{
if(prev2!=-1)
{
ret=min(ret,i-prev2);
}
prev1 = i;
}
else if(str==str2)
{
if(prev1!=-1)//去找str1
{
ret = min(ret,i-prev1);
}
prev2 = i;
}
}
if(ret == 0x3f3f3f3f) cout<<-1<<endl;
else cout<<ret<<endl;
return 0;
}
// 64 位输出请用 printf("%lld")
以上就是经典面试题,可反复练习。