0922文远知行笔试题
第一题:贪心(100分)
给一个数组arr,每次选下标i和j,对arr[i]-=1,arr[j]+=1.如果i<j,这操作免费,否则消耗一个金币。
数组长度1e5,数组的和为0.求最小对少消耗能使得所有元素变成0.
贪心思路:用ans表示消耗,用acc表示目前的累加值,顺序迭代
当acc为正时,表示当前有剩余的可以用于自减(操作免费的次数)
当acc为负时,表示需要消耗金币才能实现的操作(收费操作的次数)
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
ll ans = 0, acc = 0;
int tmp;
for (int i = 0; i < n; i++)
{
scanf("%d", &tmp);
acc += tmp;
if (acc < 0)
{
ans -= acc;
acc = 0;
}
}
cout << ans << endl;
}
return 0;
}
第二题:贪心(100分)
lc11.但是数据里1e7,并且没有输入数据的个数,数据多行,数据之间用','和' '隔开,主要是处理数据输入
用while (cin >> str)处理不定行
对于每行,先用stringstream按照','隔开,然后判断是不是存在非' '的字符(空的字符串或者全是' '组成的字符串调用stoi会报异常)
g++ wenyuan2.cpp && ./a.out terminate called after throwing an instance of 'std::invalid_argument' what(): stoi Aborted
然后就是头尾双指针贪心求解,用long long存。
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
int main()
{
string str;
vector<int> arr;
while (cin >> str)
{
stringstream ss(str);
string tmp;
while (getline(ss, tmp, ','))
{
if (tmp.find_first_not_of(' ') != string::npos)
arr.push_back(stoi(tmp));
}
}
int n = arr.size();
int l = 0, r = n - 1;
ll ans = 0;
while (l < r)
{
ans = max(ans, ll(r - l) * min(arr[l], arr[r]));
if (arr[l + 1] >= arr[r - 1])
l++;
else
r--;
}
cout << ans << endl;
return 0;
}
第三题:不会写(14.29分)
就骗了一点分(写第三题时还有一个半小时,但完全不会,连暴力解的思路都没有)

