【Problem 2】赶去公司
介绍
终于到周末啦!小易走在市区的街道上准备找朋友聚会,突然服务器发来警报,小易需要立即回公司修复这个紧急bug。假设市区是一个无限大的区域,每条街道假设坐标是(X,Y),小易当前在(0,0)街道,办公室在(gx,gy)街道上。小易周围有多个出租车打车点,小易赶去办公室有两种选择,一种就是走路去公司,另外一种就是走到一个出租车打车点,然后从打车点的位置坐出租车去公司。每次移动到相邻的街道(横向或者纵向)走路将会花费walkTime时间,打车将花费taxiTime时间。小易需要尽快赶到公司去,现在小易想知道他最快需要花费多少时间去公司。
解答
很基础的一道题目。根据题意先计算走路所需要的时间, 然后枚举taix所需要的时间, 取最小值就可以了。
#include <string>
#include <vector>
#include <utility>
#include <cstdlib>
#include <climits>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
int n; cin >> n;
vector<pair<int, int>> coordin(n, make_pair(0, 0));
for (int i = 0; i < n; ++i) { cin >> coordin[i].first; }
for (int i = 0; i < n; ++i) { cin >> coordin[i].second;}
int gx, gy;
cin >> gx, cin >> gy;
int walkTime, taxiTime;
cin >> walkTime, cin >> taxiTime;
int res = INT_MAX;
res = std::min(res, walkTime*(abs(gx) + abs(gy)));
for (int i = 0; i < n; ++i)
{
int temp = 0;
temp += walkTime*(abs(coordin[i].first) + abs(coordin[i].second));
temp += taxiTime*(abs(gx - coordin[i].first) + abs(gy - coordin[i].second));
res = std::min(res, temp);
}
cout << res << endl;
return 0;
}
【Problem 3】调整队形
介绍
在幼儿园有n个小朋友排列为一个队伍,从左到右一个挨着一个编号为(0~n-1)。其中有一些是男生,有一些是女生,男生用’B’表示,女生用’G’表示。小朋友们都很顽皮,当一个男生挨着的是女生的时候就会发生矛盾。作为幼儿园的老师,你需要让男生挨着女生或者女生挨着男生的情况最少。你只能在原队形上进行调整,每次调整只能让相邻的两个小朋友交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整多少次可以让上述情况最少。例如:
GGBBG -> GGBGB -> GGGBB
这样就使之前的两处男女相邻变为一处相邻,需要调整队形2次
解答
这道题目也不难。计算两种队形的结果 B在前G在后 以及 G在前B在后 然后取出来最小值就可以了。
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int getChangeTimes(string str)
{
if (str.size() <= 2) { return 0; }
int firstIndex = 0;
int secondIndex = 0;
int res = 0;
size_t index = 1;
while (index < str.size() && str[index] == str[index - 1])
{
++firstIndex;
++index;
}
if (index < str.size())
{
secondIndex = index;
++index;
while (index < str.size())
{
if (str[index] == str[firstIndex])
{
res += index - secondIndex;
firstIndex;
++secondIndex;
++index;
}
else
{
++index;
}
}
}
return res;
}
int main(int argc, char *argv[])
{
string str;
cin >> str;
int res = getChangeTimes(str);
for (int i = 1; i < str.size(); ++i)
{
if (str[i] != str[i - 1])
{
int temp = i;
std::swap(str[0], str[i]);
res = std::min(res, getChangeTimes(str)+temp);
std::swap(str[0], str[i]);
break;
}
}
cout << res << endl;
return 0;
}
【Problem 4】消除重复元素
介绍
小易有一个长度为n序列,小易想移除掉里面的重复元素,但是小易想是对于每种元素保留最后出现的那个。小易遇到了困难,希望你来帮助他。
解答
直接模拟就好了。
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>
using namespace std;
int main(int argc, char *argv[])
{
int n;
cin >> n;
vector<int> data(n);
for (int i = 0; i < n; ++i)
{
cin >> data[i];
}
vector<int> res;
for (int i = n - 1; i >= 0; --i)
{
if (find(res.begin(), res.end(),data[i]) == res.end())
{
res.push_back(data[i]);
}
}
for (int i = res.size() - 1; i >= 0; --i)
{
(i != 0) ? cout << res[i] << " " : cout << res[i];
}
cout << endl;
return 0;
}