华为机试 190道题 C++ 解法

[ ]包围起来的是需要读取的字符集合
例如:%[abcd]表示只读取字符abcd,遇到其它的字符就读取结束(这句话是重点)\
不匹配某些字符只需要在[ ]内的最前面加一个^就可以了
scanf() 允许把读取到的数据直接丢弃,不往变量中存放,具体方法就是在 % 后面加一个*,例如:
scanf("%*[a-z]");
scanf("%*[a-z]")表示将读取到的小写字母丢弃scanf()的一些用法
“%ns”,n为整数,读入的字符串最长不超过n,然后在末尾补’\0’
%nf 读入的浮点数最多有n位整数,位数多于n,会截断。
“%n[a-z]” 读入最多n个字符,如果遇到非a-z的字符,停止
“%[^=]” 读入任意多的字符,直到遇到"="停止
“%n[^=]” 读入"="号前的至多n 个字符
"*"表示该输入项读入后不赋予任何变量,即跳过该输入值。
比如%[0-9]表示只读入’0’到’9’之间的字符,%[a-zA-Z]表示只读入字母,
'-'是范围连接符,也可以直接列出你需要读入的字符。1、 星球争霸篮球赛  MVP    和力扣 698很像
题解:
#includeusing namespace std;vector bucket;
bool backtrack(vector &nums, int index, int target);int main()
{int t;cin >> t;vector nums;int sum = 0;int tmp;while(cin >> tmp) {sum += tmp;nums.push_back(tmp);if(cin.get() == '\n') {break;}}cout << sum <<  ' ' << t << endl;//输入的时候计算和或者用函数求和// sum = accumulate(nums.begin(),nums.end());sort(nums.rbegin(), nums.rend());for(int k = t; k > 0; k--) {cout << k << endl;if(sum%k == 0) {bucket.resize(k);int target = sum/k;bool result = backtrack(nums, 0, target);if(result) {cout << target << endl;return 0;}}}return 0;
}bool backtrack(vector &nums, int index, int target) {if(index == nums.size()){return true;}for(int i = 0; i < bucket.size(); i++) {if(bucket[i] + nums[index] > target) {continue;}if(i > 0 && bucket[i] == bucket[i-1]) {continue;}bucket[i] += nums[index];if(backtrack(nums, index+1, target)) {return true;}bucket[i] -= nums[index];}return false;
}2、 开心消消乐   dfs深度搜索
题解:
#includeusing namespace std;int dir[8][2] = {-1,-1,-1,0,-1,1,0,-1,0,1,1,-1,1,0,1,1}; // 8个方向 8*vector
void dfs(vector> &nums, int i, int j);int main()
{int n,m;cin >> n >> m;vector> nums;for(int i = 0; i < n; i++) {vector tmp;int temp;for(int j = 0; j < m; j++) {cin >> temp;tmp.push_back(temp);}nums.push_back(tmp);}//vector> visit(n,vector(m,false));int count = 0;for(int i = 0; i < n; i++) {for(int j = 0; j < m; j++) {if(nums[i][j]) {count++;dfs(nums, i, j);}}}cout << count << endl;return 0;
}void dfs(vector> &nums, int i, int j) {nums[i][j] = 0;for(int k = 0; k < 8; k++) {int nextx = i+dir[k][0];int nexty = j+dir[k][1];if(nextx < 0 || nextx >= nums.size()) {continue;}if(nexty < 0 || nexty >= nums[0].size()) {continue;}if(nums[nextx][nexty] == 0) {continue;}dfs(nums, nextx, nexty);}
}3、 特异性双端队列 、 最小调整顺序次数  、 最小的调整次数  栈、队列
题解:
#includeusing namespace std;int main() {string str;getline(cin, str);int N = stoi(str);int result = 0;bool inorder = true; // 有序int size = 0;for(int i = 0; i < N * 2; i++) {getline(cin, str);istringstream ss(str);ss >> str;if(str == "remove") {if(size == 0) {continue;} else {if(inorder == false) {result++;inorder = true;}size--;}} else {if(str == "head" && size != 0) {inorder = false;}size++;}}cout << result << endl;return 0;
}4、 微服务的集成测试    深度搜索
题解:
#include 
#include using namespace std;int countTime(vector > use, int k) {int maxtime = 0;for (int i = 0; i < use.size(); ++i) {if (use[k][i] != 0 && i != k) {maxtime = max(maxtime, countTime(use, i));}}return maxtime + use[k][k];
}int main() {int n, k;cin >> n;vector > use(n, vector(n));for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {cin >> use[i][j];}}cin >> k;int time = countTime(use, k - 1);cout << time << endl;return 0;
}5、 优选核酸检测点  排序  逻辑  分别计算去每个点的花费和做完时间,然后按照要求排序
题解:
#include 
#include 
#include 
using namespace std;struct Point {int id; // 监测点编号int dis; // 距离起点距离int que; // 排队人数int pay; // 支付金额int time; // 到达监测点的时间
};const int add8_10[] = {3, 480, 600}; // 8点到10点之间的监测点参数
const int add12_14[] = {10, 720, 840}; // 12点到14点之间的监测点参数int getTime(int start, Point& point) {int time = 0;// 累加路程时间time += point.dis * 10;// 去除路程中的排队人数  感觉这块有问题需要调整point.que = max(0, point.que - point.dis * 10);// 到监测点的时间int on = start + point.dis * 10;// 8点前到 非核酸时间没有人排队if (on <= add8_10[1]) {return add8_10[1] - start;}// 8点-10点到   8点-到达时间有新增    8点-到达时间有做完的if (on <= add8_10[2]) {point.que += (on - add8_10[1]) * add8_10[0] - (on - add8_10[1]);return time + point.que;}// 10-12点到if (on <= add12_14[1]) {return time + point.que;}// 12-14点到 12点-到达时间有新增    12点-到达时间有做完的if (on <= add12_14[2]) {point.que += (on - add12_14[1]) * add12_14[0] - (on - add12_14[1]);return time + point.que;}// 14点以后return time + point.que;
}void solution(int start, int end, vector& points) {vector res;for (auto& p : points) {if (start + p.time < end) {res.push_back(p);}}sort(res.begin(), res.end(), [](const Point& p1, const Point& p2) {if (p1.time != p2.time) { // 如果到达时间不同,按到达时间升序排列return p1.time < p2.time;} else { // 如果到达时间相同,按支付金额升序排列return p1.pay < p2.pay;}});cout << res.size() << endl; // 输出监测点数量for (auto& p : res) { // 输出每个监测点的编号、到达时间和支付金额cout << p.id << " " << p.time << " " << p.pay << endl;}
}int main() {int start_hour, start_minute, end_hour, end_minute, n;cin >> start_hour >> start_minute >> end_hour >> end_minute >> n;int start = start_hour * 60 + start_minute; // 起点时间int end = end_hour * 60 + end_minute; // 终点时间vector points(n); // 监测点数组for (int i = 0; i < n; i++) {Point point;cin >> point.id >> point.dis >> point.que;point.pay = point.dis * 10; // 支付金额point.time = getTime(start, point); // 到达监测点的时间points[i] = point;}solution(start, end, points); // 求解return 0;
}6、 核算采样的效率  动态规划  多重背包问题
题解:
dp[j]
#include 
#include 
#include 
using namespace std;int main() {int num1,num2;cin >> num1 >> num2;vector v; //效率/10for (int i = 0; i < num1; i++)  {int val;cin >> val;v.push_back(val/10);}// 志愿者多几个提升几倍效率,最多4M倍// dp[j]代表几个志愿者对应的提升效率vectordp(num2 + 1, 0);for (int i = 0; i < num1; i++) {for (int j = num2; j > 0; j--) {// 以上为01背包,然后加一个遍历个数for (int k = 1; k <= 4 && j - k >= 0; k++) { // 遍历个数dp[j] = max(dp[j], dp[j - k] + (k+1)* v[i]);}}}// 没有志愿者的时候  效率为80% 之和int sum = 0;for (int i = 0; i < num1; i++) {sum += 8*v[i];}cout << dp[num2] + sum;return 0;
}或者dp[i][j]
#include 
#include 
#include 
using namespace std;int main() {int num1,num2;cin >> num1 >> num2;vector num1Vec;vector num2Vec; //效率/10for (int i = 0; i < num1; i++)  {int val;cin >> val;num1Vec.push_back(val);num2Vec.push_back(val/10);}vector> dp(num1+1, vector(num2+1, 0));int count = 0;for(int i = 1; i < num1+1; i++) {for(int j = 1; j < num2+1; j++) {dp[i][j] = max( dp[i-1][j]+num1Vec[i-1]-2*num2Vec[i-1], dp[i-1][j-1]+num1Vec[i-1]);     //志愿者大于等于1dp[i][j] = max( dp[i][j], j-2 >= 0 ? dp[i-1][j-2]+num1Vec[i-1]+num2Vec[i-1] : 0);    //志愿者大于等于2dp[i][j] = max( dp[i][j], j-3 >= 0 ? dp[i-1][j-3]+num1Vec[i-1]+2*num2Vec[i-1] : 0);  //志愿者大于等于3dp[i][j] = max( dp[i][j], j-4 >= 0 ? dp[i-1][j-4]+num1Vec[i-1]+3*num2Vec[i-1] : 0);  //志愿者大于等于4(题目强调最多提示3M)}}cout << dp[num1][num2] << endl;return 0;
}7、 最大报酬   工作安排   动态规划
题解:
#include 
#include 
#include 
using namespace std;int main() {int T, n;cin >> T >> n;vector> timePay(n, vector(2));int val1, val2;for(int i = 0; i < n; i++) {cin >> val1 >> val2;timePay[i][0] = val1;timePay[i][1] = val2;}vector dp(T+1,0);for(int i = 0; i < n; i++) {for(int j = T; j >= timePay[i][0]; j--) {dp[j] = max(dp[j], dp[j-timePay[i][0]]+timePay[i][1]);}}cout << dp[T] << endl;return 0;
}或者贪心:
#include using namespace std;int cmp(pair a, pair b) {if(a.second == b.second) {return a.first < b.first;} else {return a.second > b.second;}
}int main() {int T, n;cin >> T >> n;vector> nums(n);for(int i = 0; i < n; i++) {int t, w;cin >> t >> w;nums.push_back(pair{t, w});}sort(nums.begin(), nums.end(), cmp);int res = 0;int timesum = 0;for(int i = 0; i < n; i++) {timesum += nums[i].first;if(timesum <= T) {res += nums[i].second;} else {timesum -= nums[i].first;}}cout << res << endl;return 0;
}8、 预订酒店   abs(value-target)按照要求排序,之选择前k个再按照从小到大排序。
题解:
#include 
#include 
#include 
#include 
#include using namespace std;vector split(string str) {vector res;stringstream  ss(str);while(getline(ss,str, ' ')) {res.push_back(stoi(str));}return res;
}int x;
bool cmp(int a, int b) {if(abs(a-x)==abs(b-x)) {return a vec=split(str);int n,k;n=vec[0],k=vec[1],x=vec[2];getline(cin,str);vector arr=split(str);sort(arr.begin(),arr.end(),cmp);vector res(arr.begin(),arr.begin()+k);sort(res.begin(),res.end());for(auto val : res) {cout << val << " ";}cout << endl;system("pause");return 0;
}9、 最接近最大输出功率的设备 /查找充电设备组合  寻找充电设备组合      回溯  或者  01背包动态规划  
题解:
#include 
#include 
#include 
#include 
#include using namespace std;bool result;
void dfs(vector& value, int target, int index) {if(target == 0) {result = true;return;}for(int i = index; i < value.size(); i++) {if(target - value[i] >= 0) {dfs(value, target-value[i], i+1);}}
}int main() {int n, p_max;cin >> n;vector value;for(int i = 0; i < n; i++) {cin >> p_max;value.push_back(p_max);}cin >> p_max;result = false;dfs(value, p_max, 0);if(result) {cout << p_max << endl;} else {cout << '0' << endl;}system("pause");return 0;
}
或者:
#include 
#include 
#include 
#include 
#include using namespace std;int main() {int n, p_max;cin >> n;vector value;for(int i = 0; i < n; i++) {cin >> p_max;value.push_back(p_max);}cin >> p_max;vector dp(p_max+1,0);for(int i = 0; i < value.size(); i++) {for(int j = p_max; j >= value[i]; j--) {dp[j] = max(dp[j], dp[j-value[i]] + value[i]);}}if(dp[p_max] == p_max) {cout << p_max << endl;} else {cout << "0" << endl;}system("pause");return 0;
}10、 单词接龙  回溯 广搜
题解:   输入不对
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;int ladderLength(string beginWord, string endWord, vector& wordList) {// 将vector转成unordered_set,提高查询速度unordered_set wordSet(wordList.begin(), wordList.end());// 如果endWord没有在wordSet出现,直接返回0if (wordSet.find(endWord) == wordSet.end()) return 0;// 记录word是否访问过unordered_map visitMap; // // 初始化队列queue que;que.push(beginWord);// 初始化visitMapvisitMap.insert(pair(beginWord, 1));while(!que.empty()) {string word = que.front();que.pop();int path = visitMap[word]; // 这个word的路径长度for (int i = 0; i < word.size(); i++) {string newWord = word; // 用一个新单词替换word,因为每次置换一个字母for (int j = 0 ; j < 26; j++) {newWord[i] = j + 'a';if (newWord == endWord) return path + 1; // 找到了end,返回path+1// wordSet出现了newWord,并且newWord没有被访问过if (wordSet.find(newWord) != wordSet.end()&& visitMap.find(newWord) == visitMap.end()) {// 添加访问信息visitMap.insert(pair(newWord, path + 1));que.push(newWord);}}}}return 0;
}int main() {string beginWord, endWord;getline(cin, beginWord);getline(cin, endWord);string str;vector wordList;while(getline(cin, str)) {wordList.push_back(str);}int result = ladderLength(beginWord, endWord, wordList);cout << result << endl;system("pause");return 0;
}11、 发现新词的数量 /新词挖掘/ 知识图谱  图谱新词挖掘1  滑动窗口
题解:
第一种方法 滑动窗口
#include 
using namespace std;
int main() {string c,w;cin >> c >> w;int clen = c.size();int wlen = w.size();int res=0;map mp2;for(int i=0;i mp1;for(int i=0;i
#include using namespace std;int findNewword(string&c, string& w) {int count = 0;for(int i = 0; i <= c.size()-w.size(); i++) {string str = c.substr(i, w.size());sort(str.begin(), str.end());if(str == w)) {count++;}}return count;
}int main() {string c, w;cin >> c >> w;if(c.size() < w.size()) {cout << '0' << endl;return 0;}sort(w.begin(), w.end());int res = findNewword(c,w);cout << res << endl;system("pause");return 0;
}12、 AI 处理器   逻辑处理
题解:
#include using namespace std;vector split(string str) {vector res;stringstream ss(str);while(getline(ss, str, ',')) {res.push_back(stoi(str));}return res;
}int main(){string str;getline(cin, str);int val;cin >> val;vector vec = split(str.substr(1,str.size()-2));int v1 = 0;int v2 = 0;vector vis(8);for(int i = 0; i < vec.size(); i++) {if(vec[i]<4) {v1++;}else{v2++;}vis[vec[i]] = 1;}vector> ans;if (val == 1) {//申请1个处理器int state = 0;//亲和度判断if (v1 == 1 || v2 == 1) state = 1;else if (v1 == 3 || v2 == 3) state = 3;else if (v1 == 2 || v2 == 2) state = 2;else if (v1 == 4 || v2 == 4) state = 4;if (v1 == state) {for (int i = 0; i < 4; i++) {if (vis[i] == 1) {vector tmp;tmp.push_back(i);ans.push_back(tmp);}}}if (v2 == state) {for (int i = 4; i < 8; i++) {if (vis[i] == 1) {vector tmp;tmp.push_back(i);ans.push_back(tmp);}}}} else if (val == 2) {//申请2个处理器int state = 0;if (v1 == 2 || v2 == 2) state = 2;else if (v1 == 4 || v2 == 4) state = 4;else if (v1 == 3 || v2 == 3) state = 3;if (v1 == state) {for (int i = 0; i < 4; i++) {for (int j = i + 1; j < 4; j++) {if (i != j && vis[i] == 1 && vis[j] == 1) {vector tmp;tmp.push_back(i);tmp.push_back(j);ans.push_back(tmp);}}}}if (v2 == state) {for (int i = 4; i < 8; i++) {for (int j = i + 1; j < 8; j++) {if (i != j && vis[i] == 1 && vis[j] == 1) {vector tmp;tmp.push_back(i);tmp.push_back(j);ans.push_back(tmp);}}}}} else if (val == 4) {cout<<"[";//申请4个处理器if (v1 == 4) {cout<<"[0,1,2,3]";}if (v2 == 4) {if(v1 == 4) cout<<",";cout<<"[4,5,6,7]";}cout << "]";} else if (val == 8) {if(vec.size()==8) {cout<<"[0,1,2,3,4,5,6,7]";}else{cout<<"[]";}}cout<<"[";int i=0;for(auto se:ans) {i++;cout<<"[";for(int i=0;i
#include
#include
#includeusing namespace std;int cmp(vector a, vector b) {if(a[0] != b[0]) {return a[0] < b[0];} else {return a[1] > b[1];}
}int main() {int N;cin >> N;map>> mp;int index = 1;string res;for(int i = 0; i < N; i++) {string s;cin >> s;if(s[0] == 'I') {int P, L;cin >> P >> L;mp[P].push_back({L, index});index++;} else {int P;cin >> P;if(mp[P].size() > 0) {sort(mp[P].begin(), mp[P].end(), cmp);int ind = mp[P].back()[1];mp[P].pop_back();cout << ind << endl;} else {cout << "NULL" << endl;}}}system("pause");return 0;
}14、 IPv4地址转换成整数  字符串处理   位变化 <<   >> 
题解:
#include
#include
#include
#include
#include 
#includeusing namespace std;int main() {string str;getline(cin, str);stringstream ss(str);vector ipvalue;int point = -1;while(getline(ss, str, '#')) {int val = stoi(str);if(val < 1 || val > 255) {cout << "invalid IP" << endl;system("pause");return 0;}ipvalue.push_back(val);point++;}if(point < 3 || ipvalue.size() != 4) {cout << "invalid IP" << endl;system("pause");return 0;}long long res;for(int i = 0; i < ipvalue.size(); i++) {res += ipvalue[i] << (point-i)*8;}cout << res << endl;system("pause");return 0;
}或者 c  scanf处理
#includeint validip(int* arr) {if(arr[0] < 1 || arr[0] > 128) {return 0;}for (int i = 1; i < 4; i++) {if (arr[i] > 255 || arr[i] < 0)return 0;}return 1;
}int main() {int ip[4] = { -1,-1,-1,-1 };while (scanf("%d#%d#%d#%d", ip, ip+1,ip+2,ip+3) != EOF) {if (!validip(ip)) printf("1\n");else {unsigned u = 0;for (int i = 0; i < 4; i++)u = u * 256 + ip[i];printf("%d", u);}}
}15、 最远足迹  、 洞穴探险
题解:字符串处理
#include
#include
#include
#include
#includeusing namespace std;int main() {string str;getline(cin, str);vector> vec;for(int left = 0, right; left < str.size(); left++) {if(str[left] == '(') {right = left + 1;while(str[right] != ')') {right++;}string temp = str.substr(left+1, right- left - 1);stringstream ss(temp);vector point;while(getline(ss, temp, ',')) {point.push_back(temp);}vec.push_back(point);left = right+1;}}int max = 0;int maxindex = -1;for(int i = 0; i < vec.size(); i++) {string leftvalue = vec[i][0];string rightvalue = vec[i][1];if(leftvalue[0] == '0' || rightvalue[0] == '0') {continue;}int left = stoi(leftvalue);int right = stoi(rightvalue);if(left <= 0 || left >= 10000 || right <= 0 || right >= 10000) {continue;}int tempsum = (left * left) + (right * right);if(tempsum > max) {max = tempsum;maxindex = i;}}if(max == 0 || maxindex == -1) {cout << "(0,0)" <
#include
#include
#includeusing namespace std;int main() {int m, n;cin >> m >> n;if(m > n) {cout << -1;return 0;}vector fields(m);int maxvalue = 0;for(int i = 0; i < m; i++) {cin >> fields[i];maxvalue = max(maxvalue,fields[i]);}if(m == n) {cout << maxvalue;return 0;}sort(fields.begin(), fields.end());int left = fields[0];int right = fields[m-1];int result = -1;while(left < right) {int mid = left + (right - left)/2;int res = 0;for(int i = 0; i < m; i++) {if(fields[i]%mid == 0) {res += fields[i]/mid;} else {res += fields[i]/mid + 1;}}if(res == n) {result = mid;break;} else if(res > n) {left = mid;} else {right = mid;result = mid;}}cout << result << endl;system("pause");return 0;
}17、 整理扑克牌  逻辑 排序
题解:
#includeusing namespace std;bool cmp(pair x, pair y) {if (x.second == y.second) {return y.first nums;while(cin >> tmp) {nums.push_back(tmp);if(cin.get() == '\n') {break;}}//key为牌面点数,value为该点数的张数map card;for (int i=0;i> card_vec(card.begin(),card.end());//排序,先按张数排序,再按点数排序sort(card_vec.begin(), card_vec.end(), cmp); // 特殊情况处理string result = "";vector split_cards;  for(int i=0; i temp = card_vec[i];int carNum = temp.first;int carCount = temp.second;// 3+3的情况,要拆分成葫芦if(i > 0 && card_vec[i-1].second == 3 && carCount == 3){split_cards.push_back(carNum);carCount = 2;temp.second = 2;// 给拆分的牌也组合一下}else if(carCount == 1 && split_cards.size() != 0){ for (int k=0; k carNum){    result += to_string(split_cards[k]) + " ";split_cards.erase(split_cards.begin() + k); k--;   }}}for(int j=0; j
#include
#includeusing namespace std;int main() {int N, M;cin >> N >> M;vector vec(N,1);int k;for(int i = 0; i < M; i++) {cin >> k;vec[k - 1] = 0;}cin >> k;int left = 0;int right = 0;int count = 0;int maxlen = 0;while(right < vec.size()) {if(vec[right] == 0) {count++;}while(count > k) {if(vec[left++] == 0) {count--;}}maxlen = max(maxlen, right - left + 1);right++;}cout << maxlen << endl;system("pause");return 0;
}19、 分班问题  、 分班
题解:字符串处理
#include
#include
#includeusing namespace std;vector split(string str) {int pos = str.find('/');vector res;res.push_back(str.substr(0,pos));res.push_back(str.substr(pos+1));return res;
}int main(){string str;vector> vec;while(cin >> str) {vector tmp = split(str);vec.push_back(tmp);if(cin.get() == '\n') {break;}}vector a;vector b;int ban = 1;for(int i = 0; i < vec.size(); i++) {int num = stoi(vec[i][0]);if(num < 0 || num > 999) {cout << "ERROR" << endl;return 0;}if(i == 0) {a.push_back(num);continue;}if(ban == 1) {if(vec[i][1][vec[i][1].size()-1] == 'Y') {a.push_back(num);} else {b.push_back(num);ban = 2;}} else { if(vec[i][1][vec[i][1].size()-1] == 'Y') {b.push_back(num);} else {a.push_back(num);ban = 1;}}}sort(a.begin(), a.end());sort(b.begin(), b.end());vector> res;res.push_back(a);res.push_back(b);sort(res.begin(), res.end());for(int i = 0; i < res.size(); i++) {if(res[i].size() == 0) {continue;}for(int j = 0; j < res[i].size(); j++) {cout << res[i][j] << ' ';}cout << endl;}return 0;
}20、 分苹果   异或
题解:
#includeusing namespace std;int main(){int num;cin >> num;vector nums;int sum = 0;int tmp = 0;int minnum = 100001;while(cin >> num) {nums.push_back(num);tmp ^= num;sum += num;minnum = min(minnum, num);if(cin.get() == '\n') {break;}}if(tmp == 0) {cout << sum - minnum << endl;} else {cout << -1 << endl;}return 0;
}21、 高矮个子排队  逻辑处理
题解:    
#include
#includeusing namespace std;int main() {vector heights;int height;while(cin >> height) {heights.push_back(height);char ch = cin.get();if(ch == '\n') {break;}        if(ch != ' ') {cout << "[]" << endl;return 0;}}for(int i = 0; i < heights.size(); i++) {if(i % 2 == 0 && i < heights.size()-1 && heights[i] < heights[i+1]) {swap(heights[i], heights[i+1]);}if(i % 2 == 1 && i < heights.size()-1 && heights[i] > heights[i+1]) {swap(heights[i], heights[i+1]);}if(i != 0) {cout << ' ';}cout << heights[i];}cout << endl;return 0;
}22、 路灯照明1 路灯照明问题 逻辑处理
题解:
#include
#include
#include
#include
#includeusing namespace std;int main() {int n, l;cin >> n >> l;vector nums(n);for(int i = 0; i < n; i++) {cin >> nums[i];}sort(nums.begin(), nums.end());double res = nums[1] - nums[0];for(int i = 1; i < n-1; i++) {if(res < nums[i+1] - nums[i])res = nums[i+1] - nums[i];}res /= 2;if(nums[0] > res) {res = nums[0];}if(l - nums[n-1] > res) {res = l - nums[n-1];}printf("%.2lf", res);return 0;
}23、 路灯照明2   合并区间    贪心
题解:
方案一 贪心尝试:
#include
#include
#includeusing namespace std;int main() {int n;cin >> n;vector nums(n);for(int i = 0; i < n; i++) {cin >> nums[i];}int res = 0;for(int i = 0; i < n-1; i++) {if(100 > (nums[i+1] + nums[i])) {res += 100 - (nums[i+1] + nums[i]);}}cout << res << endl;return 0;
}方案二 区间合并:
#include
#include
#includeusing namespace std;int cmp(vector a, vector b) {if(a[0] == b[0]) {return  b[1] > a[1];}return a[0] < b[0];
}int main() {int n;cin >> n;vector> nums;int x;for(int i = 0; i < n; i++) {cin >> x;nums.push_back(vector{i*100-x, i*100+x});}sort(nums.begin(), nums.end(), cmp);int res = 0;int end = nums[0][1];for(int i = 1; i < n; i++) {if(end < nums[i][0]) {res += nums[i][0] - end;}end = nums[i][1];}cout << res << endl;return 0;
}24、 需要打开多少监视器(监控) 广度优先 或者 数据小直接逻辑处理 
题解:
第一种方法:
#include
#include
#includeusing namespace std;int main() {int m, n;cin >> m >> n;vector> nums(m, vector(n , 0));for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {cin >> nums[i][j];}}vector> dis{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};int result = 0;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(nums[i][j]) {result++;continue;}for(int k = 0; k < 4; k++) {int nextx = i + dis[k][0]; int nexty = j + dis[k][1];if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && nums[nextx][nexty]) {result++;break;}}}}cout << result;return 0;
}第二种bfs:
#include
#include
#includeusing namespace std;vector> dis{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};void bfs(vector>& nums, int x, int y) {for(int i = 0; i < 4; i++) {int nextx = x + dis[i][0];int nexty = y + dis[i][1];if(nextx < 0 || nextx >= nums.size()) {continue;}if(nexty < 0 || nexty >= nums[0].size()) {continue;}if(nums[nextx][nexty] == 0) {nums[nextx][nexty] = 2;}}
}
int main() {int m, n;cin >> m >> n;vector> nums(m, vector(n , 0));for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {cin >> nums[i][j];}}for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(nums[i][j] == 1) {bfs(nums, i, j);}}}int count = 0;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(nums[i][j]) {count++;}}}cout << count;return 0;
}25、 整数编码  进制转换  字符串处理
题解:
#include
#include
#include
#include
#include
#includeusing namespace std;string decimalToBinary(int num) {string binary;if (num == 0) {binary += '0'; // Special case for input value 0} else {while (num > 0) {binary  += '0' + num % 2;num /= 2;}}reverse(binary.begin(), binary.end());return binary;
}void solution(int num) {string binary = decimalToBinary(num);cout << binary << endl;string builder;int i = binary.size();while (i > 0) {string binString;if (i >= 7) {if (i > 7) {// 剩余的超过7位,说明还有,用1补位binString.append("1");}binString.append(binary, i - 7, 7);i -= 7;} else {// 少于7位,用0补位for (int j = 0; j < 8 - i; j++) {binString.append("0");}binString.append(binary, 0, i);i = 0;}long int temp = stoi(binString, nullptr, 2);stringstream ss;ss << uppercase << setw(2) << setfill('0') << hex << temp << endl;ss >> binString;builder.append(binString);  }cout << builder << endl;
}int main() {int num;cin >> num;solution(num);return 0;
}26、 五子棋迷  、  竖直五子棋  
题解:滑动串口
#include 
using namespace std;int main()
{int x = 1;cin >> x;vector vec;int num;// 因为长度未知,所以直到读不到数为止,这是一个数组,有若干个数while (cin >> num) vec.push_back(num);// 找到当前子在未落子前的最大连续长度 cur_maxint cur_max = 0;for (int i = 0, j = 0; i < vec.size(); ++i) {if (vec[i] == x) j += 1;else j = 0;cur_max = max(cur_max, j);}// len[i] 表示落子到 i 这个位置,包含 i 这个位置的当前子的最大长度vector len(vec.size());// max_len 表示落子后,包含当前落子位置的最大连续长度int max_len = 0;for (int i = 0; i < vec.size(); ++i) {if (vec[i] == 0) {int L = i - 1, R = i + 1;// 向左while (L >= 0 && vec[L] == x) L -= 1;// 向右while (R < vec.size() && vec[R] == x) R += 1;// 只有 <= 5 才合法if (R - L - 1 <= 5) {len[i] = R - L - 1;max_len = max(max_len, R - L - 1);}}}// 如果 max_len 小于 cur_max,说明不存在答案if (max_len <= cur_max || vec.empty()) {cout << "-1\n";return 0;}// 否则找距离中间位置最近的一个点,其落子后的连续长度最长int ansidx = -1;int mid = (vec.size() - 1) / 2;for (int i = 0; i < vec.size(); ++i) {if (len[i] > cur_max) {if (ansidx == -1 || abs(ansidx - mid) > abs(i - mid)) {ansidx = i;}}}cout << ansidx << "\n";return 0;
}27、 阿里巴巴找黄金宝箱 Ⅰ  前缀和
题解:  前缀和 左边和等于右边和的坐标
#include
#include
#includeusing namespace std;int main() {string str;getline(cin, str);stringstream ss(str);vector nums;int right = 0;while(getline(ss ,str, ',')) {nums.push_back(stoi(str));right += nums.back();}int left = 0;for(int i = 0; i < nums.size(); i++) {right -= nums[i];if(left == right) {cout << i << endl;return 0;}left += nums[i];}cout << "-1" << endl;return 0;
}或者前缀和:
#include
#include
#includeusing namespace std;int main() {string str;getline(cin, str);stringstream ss(str);vector pre;pre.push_back(0);while(getline(ss ,str, ',')) {pre.push_back(pre.back()+stoi(str));}for(int i = 1; i < pre.size(); i++) {if(pre[i-1] == pre[pre.size()-1] - pre[i]) {cout << i-1 << endl;return 0;}}cout << "-1" << endl;return 0;
}28、 阿里巴巴找黄金宝箱 Ⅱ  hash
题解:   删除几类数,可以删掉nums的一半以上
#include
#include
#include
#include
#include
#includeusing namespace std;int cmp(pair a, pair b) {return a.second > b.second;
}int main() {string str;getline(cin, str);stringstream ss(str);map mp; int size = 0;while(getline(ss, str, ',')) {if(mp.find(str) != mp.end()) {mp[str]++;}else{mp[str] = 1;}size++;}vector> vec(mp.begin(), mp.end());sort(vec.begin(), vec.end(), cmp);int sum = 0;int result = 1;for(int i = 0; i < vec.size(); i++) {sum += vec[i].second;if(sum < size/2) {result++;}}cout << result << endl;return 0;
}29、  字母消消乐 消消乐游戏 字符串消除  stack
题解:
#include
#includeusing namespace std;int main() {string input;char tmp;while(cin >> tmp) {if((tmp >= 'a' && tmp <= 'z') || (tmp >= 'A' && tmp <= 'Z')) {if(!input.empty() && input.back() == tmp) {input.pop_back();}else {input.push_back(tmp);}} else {cout << '0' << endl;return 0;}}cout << input.size() << endl;return 0;
}30、 事件的推送  事件推送   逻辑处理
题解:
#include
#includeusing namespace std;int main() {int m, n, r;cin >> m >> n >> r;vector numsm(m);vector numsn(n);for(int i = 0; i < m; i++) {cin >> numsm[i];}for(int i = 0; i < n; i++) {cin >> numsn[i];}int i = 0, j = 0;while(i < m) {if(numsm[i] <= numsn[j] && numsn[j] - numsm[i] <= r) {cout << numsm[i] << ' ' << numsn[j] << endl;i++;}j++;}return 0;
}31、 矩阵最大值 矩阵最值 计算二位矩阵的最大值  字符串处理
题解:
#include
#include
#include
#includeusing namespace std;int main() {int n;cin >> n;vector vec;for(int i =0; i < n; i++) {string str;cin >> str;while(str.find(',') != string::npos) {str.erase(str.find(','), 1);}vec.push_back(str);}int result = 0;for(auto val : vec) {int maxnum = 0;for(int i = 0; i < val.size(); i++) {val.append(string(1, val[0]));val.erase(0,1);maxnum = max(maxnum, stoi(val, nullptr, 2));}result += maxnum;}cout << result << endl;return 0;
}32、 出租车计费  靠谱的车  逻辑处理  
题解:
#includeusing namespace std;int main() {int n;cin >> n;int res = n, temp = 0, k = 0, j = 1;while(n > 0) {if(n % 10 > 4) {temp += k * (n % 10 - 1) + j; } else {temp += k * (n % 10);}k = k * 9 + j;j *= 10;n /= 10;}cout << res - temp << endl;return 0;
}33、 没有回文串   首先归纳推出非回文的标志语句,是s[i] != s[i-1]&& s[i] != s[i-2],然后用 dfs 搜索字典序增大 
题解:
#include
#include
#includeusing namespace std;bool loopsolution(string& str, int& index) {if((index >= 1 && str[index] == str[index-1]) || (index >= 2 && str[index] == str[index-2])) {return true;}return false;
}int main() {int n;cin >> n;string str;cin >> str;string result;int index = str.size() - 1;while(1) {if(index == str.size()) {result = str;break;}if(index < 0) {result = "NO";break;}if(str[index] - 'a' + 1 == n) {str[index] = 'a' - 1;index--;} else {int tmp = (str[index] - 'a' + 1) % n;str[index] = 'a' + tmp;if(!loopsolution(str, index)) {index++;}}}cout << result << endl;return 0;
}34、  找车位   停车找车位  停车场到最近车的最远距离 
题解:
#includeusing namespace std;int main(){string s;cin >> s;stringstream ss(s);vector vec;while(getline(ss, s, ',')) {vec.push_back(stoi(s));}int ans = 0;for(int i = 0, j; i < vec.size(); i++) {if(vec[i] == 1) {j = i + 1;while(vec[j] == 0) {j++;}ans = max(ans, j - i);i = j;}}cout << ans/2;return 0;
}35、  5键键盘的输出  字符串处理
题解:
#include
#includeusing namespace std;int main() {int tmp;string cut = "";string result = "";bool flag = true; //全选操作时,flag为truewhile(cin >> tmp) {if(tmp == 1) {if(flag){result = "a";flag = false;} else {result += "a";}}else if(tmp == 2) { //复制if(flag) {cut = result; //屏幕到剪切板}}else if(tmp == 3) { //剪切if(flag) {cut = result; //屏幕到剪切result = ""; //清空屏幕}} else if(tmp == 4) { //粘贴if(flag) {result = cut; // 剪切到屏幕flag = false;} else {result += cut;}} else if(tmp == 5){ //全选flag = true;}}cout << result.size() << endl;return 0;
}36、  找到它 单词搜索   dfs深度搜索
题解:
#include
#include
#include
#includeusing namespace std;bool found = false;
int dis[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};void dfs(vector>& vec, string& str, int i, int j, int index, vector>& vis){if(index == str.size() - 1) {found = true;return;}vis[i][j] = true;for(int k = 0; k < 4; k++) {int nextx = i + dis[k][0];int nexty = j + dis[k][1];if(nextx < 0 || nextx >= vec.size() || nexty < 0 || nexty >= vec[0].size() || vis[nextx][nexty] || vec[nextx][nexty] != str[index+1]) {continue;}dfs(vec, str, nextx, nexty, index+1, vis);}vis[i][j] = false;}int main() {int m, n;cin >> m >> n;string str;cin >> str;vector> vec(m, vector(n));for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {cin >> vec[i][j];}}vector> vis(m, vector(n, false));for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(vec[i][j] == str[0]) {dfs(vec, str, i, j, 0, vis);if(found) {cout << i + 1 << ' ' <<  j + 1 << endl;return 0;}}}}cout << "NO" << endl;return 0;
}37、  找终点   最小步骤数    递归
题解:
#include
#include
#includeusing namespace std;int accuStep(vector& vec, int cur, int next, int& step) {int numstep = vec[cur];if(next == vec.size() - 1) {return step;} else if(next < vec.size() -1) {step++;return accuStep(vec, next, next + numstep, step);} else {return -1;}
}int main() {int tmp;vector vec;while(cin >> tmp) {vec.push_back(tmp);if(cin.get() == '\n') {break;}}vector use;int step = 0;for(int i = 1; i < vec.size()/2; i++) {step = 1;use.push_back(accuStep(vec, i, i, step));}for(auto iter = use.begin(); iter != use.end(); ){if( *iter == -1)iter = use.erase(iter);elseiter ++ ; }sort(use.begin(), use.end());if(use.size() != 0) {cout << use[0] << endl;} else {cout << -1 << endl;}return 0; 
}38、  We Are A Team
题解:
#include#define N 1000
int g_usr[N];void init()
{int i;for(i = 0; i < N; i++) {g_usr[i] = i;}
}void Print()
{int i;printf("The list statte: \n");for(i =0; i < 5; i++) {printf("%3d", g_usr[i]);}printf("\n");
}int getF(int t)
{if(g_usr[t] == t) {return t;} else {g_usr[t] = getF(g_usr[t]);return g_usr[t];}
}void merge(int v, int u)
{int t1 = getF(v);int t2 = getF(u);if(t1 != t2) {g_usr[t2] = t1;}Print();
}void check(int v, int u)
{int t1 = getF(v);int t2 = getF(u);Print();if(t1 != t2) {printf("we are not a family\n");} else {printf("we are a family\n");}
}int main()
{int a.b.c;init();while(1){scanf("%d %d %d", &a, &b, &c);if(c == 0) {merge(a, b);continue;}if(c == 1) {check(a, b);continue;}printf("da pian zi\n");}return 0;
}39、 仿 LISP 运算    
题解:   参考逆波兰表达式
#include 
#include 
#include 
#include using namespace std;// 判断字符串是不是约定的操作符
// add:加法
// sub:减法
// mul:乘法
// div:除法
string accu(stack& input) {if(input.size() < 3) {return "error";}int second = stoi(input.top());input.pop();int first = stoi(input.top());input.pop();string opert = input.top();input.pop();int res = 0;if(opert == "add") {res = first + second;} else if(opert == "sub") {res = first - second;}else if(opert == "mul") {res = first * second;}else {if(second == 0) {return "error";} else {res = first / second;}}return to_string(res);
}string lisp_like(string& str) {stack input;for(int i = 0; i < str.size(); ) {if(str[i] == '(') {input.push(str.substr(i+1, 3));i += 4;} else if((str[i] >= '0' && str[i] <= '9') || str[i] == '-') {int j = i;while(j < str.size() && str[j] != ' ' && str[j] != ')') {j++;}input.push(str.substr(i, j-i));i = j;} else if(str[i] == ' ') {i++;} else {string ans = accu(input);if(ans == "error") {return "error";}input.push(ans);i++;}}return input.empty() ? "0" : input.top();
}int main(const int argc, const char* argv[])
{string input;while(getline(cin, input)){if(input == "bye")break;cout << lisp_like(input) << endl;}return 0;
}40、 字符串加密  Attack AT DAWN(黎明时攻击)就会被加密为Tpptad TP ITVH 
题解:
#include 
#include 
using namespace std;int main(){string s1,s2;while(cin>>s1>>s2){string s="abcdefghijklmnopqrstuvwxyz";int i=0;while(i=s1.size(),返回nposwhile(j != string::npos){s1.erase(s1.begin()+j);  //删掉密匙中的重复字符; j=s1.find(s[i],j);}s.erase(s.begin()+i);   //去掉s中的密匙;} else {++i;}}s = s1 + s;    //构成密码本;s1="";for(int i=0;i
#include
#includeusing namespace std;bool check(pair point, vector> points) {for (auto x : points) {if (x.first == point.first && x.second == point.second) {return true;}}return false;
} int main() {int n;cin >> n;if(n < 4) {cout << 0;return 0;}vector> vec;for(int i = 0; i < n; i++) {int a, b;cin >> a >> b;vec.push_back(make_pair(a, b));}int count = 0;for(int i = 0; i < vec.size(); i++) {for(int j = i + 1; j < vec.size(); j++) {int x1 =  vec[i].first;int y1 =  vec[i].second;int x2 =  vec[j].first;int y2 =  vec[j].second;int x3 = x1 - (y1 - y2);int y3 = y1 + (x1 - x2);int x4 = x2 - (y1 - y2);int y4 = y2 + (x1 - x2);// 判断是否有这个点if (check(make_pair(x3, y3), vec) && check(make_pair(x4, y4), vec)) {count += 1;}int x3_2 = x1 + (y1 - y2);int y3_2 = y1 - (x1 - x2);int x4_2 = x2 + (y1 - y2);int y4_2 = y2 - (x1 - x2);if (check(make_pair(x3_2, y3_2), vec) && check(make_pair(x4_2, y4_2), vec)) {count += 1;}}}cout << count/4 << endl;return 0;
} 42、 工号不够用了怎么办    逻辑能力
题解:
#include
#include
#includeusing namespace std;int main() {int total, num;cin >> total >> num;if(total <= 26) {cout << 1 << endl;return 0;}int del = 1;for(int i = 0; i < num; i++) {del *= 26;}int res = 1;del *= 10;while(del < total) {del *= 10;res++;}cout << res  << endl;return 0;
}43、 数组去重和排序 、    数组排序  
题解: 数据结构 排序
#include
#include
#include
#include
#includeusing namespace std;int cmp(pair a, pair b) {if(a.second == b.second) {return a.first < b.first;} else {return a.second > b.second;}
}int main() {string str;getline(cin, str);stringstream ss(str);map mp;while(getline(ss, str, ',')) {int tmp = stoi(str);if(mp.find(tmp) != mp.end()) {mp[tmp]++;} else {mp[tmp] = 1;}}vector> vec(mp.begin(), mp.end());sort(vec.begin(), vec.end(), cmp);for(int i = 0; i < vec.size()-1; i++) {cout << vec[i].first << ',';}cout << vec.back().first << endl;return 0;
}44、 第K个排列     数学知识
题解:
#include
#include
#include
#include
#includeusing namespace std;string getPermutation(int n, int k) {vector factorial(n);factorial[0] = 1;for (int i = 1; i < n; i++) {factorial[i] = i * factorial[i - 1];}k--;string ans;vector nums;for (int i = 1; i <= n; i++) {nums.push_back(i);}for (int i = 1; i <= n; i++) {int order = k / factorial[n - i];ans.push_back(nums[order] + '0');for (int j = order; j < n - i; j++) {nums[j] = nums[j + 1];}k %= factorial[n - i];}return ans;
}int main() {int n, k;cin >> n >> k;string ans = getPermutation(n, k);cout << ans << endl;return 0;
}45、 打印任务排序  数据结构
题解:
#include
#include
#include
#includeusing namespace std;int cmp(pair a, pair b) {if(a.second == b.second) {return a.first < b.first;} else {return a.second > b.second;}
}int main() {string str;getline(cin, str);stringstream ss(str);vector> vec;int i = 0;while(getline(ss, str, ',')) {vec.push_back({i, stoi(str)});i++;}sort(vec.begin(), vec.end(), cmp);for(int i = 0; i < vec.size()-1; i++) {cout << vec[i].first << ',';}cout << vec.back().first << endl;return 0;	
}46、 考勤信息   字符串处理
题解:
#include
#include
#include
#includeusing namespace std;int main() {int times;cin >> times;cin.get();while(times--) {string input;getline(cin, input);vector vec;stringstream ss(input);while(getline(ss, input, ' ')) {vec.push_back(input);}int flag = false;int absentNum = 0;int faultNum = 0;for(int i = 0; i < vec.size(); i++) {if(i >= 1 && (vec[i] == "leaveearly" || vec[i] == "late")) {if(vec[i] == vec[i-1]) {cout << "false" << endl;continue;}}if(vec[i] == "absent") {absentNum++;faultNum++;}if(vec[i] == "leaveearly" || vec[i] == "late") {faultNum++;}if(i >= 6) {if(faultNum > 3) {cout << "false" << endl;continue;}if(vec[i - 6] != "present") {faultNum--;}}}if(absentNum > 1) {cout << "false" <
#include
#include
#includeusing namespace std;int main() {string input;getline(cin, input);vector vec;stringstream ss(input);while(getline(ss, input, ',')) {vec.push_back(stoi(input));}vector dp(vec.size(), 0);for(int i =0; i < dp.size(); i++) {if(i == 0) {dp[0] = max(0, vec[0]);} else if( i < 3) {dp[i] = max(0, dp[i-1] + vec[i]);} else {dp[i] = max(dp[i-3], dp[i-1] + vec[i]);}}cout << dp[dp.size()-1] << endl;return 0;	
}48、 字符串比较   |A[i] - B[i]|滑动窗口
题解:
#include 
using namespace std;int main()
{string A,B;int V;cin >>A>>B>>V;int len=A.size();vector absnum;for(int i = 0; i < len; i++) {absnum.push_back(abs(A[i] - B[i]));}int res=0; int sum = 0;int i = 0, j = 0;while(j < absnum.size()) {sum += absnum[j];if(sum > V) {while(i <= j && sum > V) {sum -= absnum[i++];}}res = max(res, j-i+1);j++;}cout << res <
using namespace std;int main()
{string input;cin >> input;while(input.find(',') != string::npos) {input.erase(input.find(',') , 1);}int i = 0, j = 0, res = 0;while(j < input.size()) {if(input[j] == '1') {i = j;while(input[j] == '1' && (j-i+1 <= 3)) {j++;}res++;}j++;}cout << res  << endl;return 0;
}50、 用户调度问题  
题解:
#include 
using namespace std;int main()
{int n;cin >> n;vector> users(n, vector(3));for(int i = 0; i < n; i++) {for(int j = 0; j < 3; j++) {cin >> users[i][j];}}vector> dp(n, vector(3, 0));for(int j = 0; j < 3; j++) {dp[0][j] = users[0][j];}for(int i = 1; i < n; i++) {dp[i][0] = users[i][0] + min(dp[i-1][1], dp[i-1][2]);dp[i][1] = users[i][1] + min(dp[i-1][0], dp[i-1][2]);dp[i][2] = users[i][2] + min(dp[i-1][0], dp[i-1][1]);}cout << min(dp[n-1][0],  min(dp[n -1][1], dp[n-1][2])) << endl;return 0;
}51、 社交距离 选座位
题解:   疫情公司开会座位
#include 
#include 
#include 
#include using namespace std;int getindex(vector& location) {int len = location.size();vector left(len, len), right(len, len);for(int i = 0; i  0) {left[i] = left[i-1] + 1;} else {left[i] = len;}}for(int i = len - 1; i >= 0; i--) {if(location[i] == 1) {right[i] = 0;} else if(i == len - 1) {right[i] = len;} else {right[i] =  right[i+1] + 1;}}int max = 0, index = -1;int count = 0;for(int i = len - 1; i >= 0; i--) {if(location[i] == 0) {int temp = min(left[i], right[i]);if(temp >= max) {max = temp;index = i;}} else {count++;}}if(count == 0) {return 0;} else if(count == len) {return -1;} else {return index;}
}int main() {int N;cin >> N;string str;cin >> str;str = str.substr(1, str.size()-2);stringstream ss(str);vector arr;while(getline(ss, str, ',')) {arr.push_back(stoi(str));}int res = -1;vector location(N, 0);for(auto val : arr) {if(val == 1) {int index = getindex(location);if(index != -1) {location[index] = 1;}res = index;} else {location[abs(val)] = 0;}}cout << res << endl;return 0;
}52、 按身高和体重排队  按身高体重排队
题解:
#include
#include
#includetypedef struct {int index;int gao;int zhong;
}Value;int cmp(const void* a, const void* b) {Value* vala = (Value*)a;Value* valb = (Value*)b;if(vala->gao == valb->gao) {return (int)(vala->zhong - valb->zhong);} else {return (int)(vala->gao - valb->gao);}
}int main()
{int n;scanf("%d", &n);Value data[n], temp;for(int i = 0; i < n; i++) {data[i].index = i+1;scanf("%d", &data[i].gao);}for(int i = 0; i < n; i++)scanf("%d", &data[i].zhong);qsort(data, n, sizeof(Value), cmp);for(int i = 0; i < n; i++) {printf("%d ", data[i].index);}system("pause");
}53、 按索引范围翻转文章片段  、 指定区域单词翻转 字符串处理
题解:
#include 
#include 
#include using namespace std;int main() {int start, end, n = 0;string str, word, nstr;getline(cin, str);stringstream ss(str);cin>>start>>end;vector arr;while (ss>>word) {arr.push_back(word);}if (start>=arr.size() || start>end || end>arr.size()) {cout<=start; --i) {if (nstr.size() == 0) {nstr = arr[i];} else {nstr = nstr + " " + arr[i];}}for (int i=end+1; i
#include
#include
#include
#includeusing namespace std;bool found = false;
int dis[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};void dfs(vector>& vec, string& str, int i, int j, int index, vector>& vis, vector& res){if(index == str.size() - 1) {found = true;return;}vis[i][j] = true;res.push_back(i);res.push_back(j);for(int k = 0; k < 4; k++) {int nextx = i + dis[k][0];int nexty = j + dis[k][1];if(nextx < 0 || nextx >= vec.size() || nexty < 0 || nexty >= vec[0].size() || vis[nextx][nexty] || vec[nextx][nexty] != str[index+1]) {continue;}dfs(vec, str, nextx, nexty, index+1, vis, res);}vis[i][j] = false;
}int main() {int m;cin >> m;string str;vector> vec;for(int i = 0; i < m; i++) {cin >> str;replace(str.begin(),str.end(),',',' ');stringstream ss(str);char temp;vector value;while(ss >> temp) {value.push_back(temp);}vec.push_back(value);}cin >> str;int n = vec[0].size();vector> vis(m, vector(n, false));vector res;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(vec[i][j] == str[0]) {res.clear();dfs(vec, str, i, j, 0, vis, res);if(found) {for(auto x : res) {cout << x << ",";}return 0;}}res.clear();}}cout << "NO" << endl;return 0;
}55、 矩形相交 的面积     空间思维能力
题解:
#include
#include
#include
#include
#includeusing namespace std;int main() {vector> vec;int n = 0;while(n < 3) {vector value;int val;while(cin >> val) {value.push_back(val);if(cin.get() == '\n') {n++;vec.push_back(value);break;}}}int left_x = max({vec[0][0], vec[1][0], vec[2][0]});int left_y = min({vec[0][1], vec[1][1], vec[2][1]});int right_x = min({vec[0][0]+vec[0][2], vec[1][0]+vec[1][2], vec[2][0]+vec[2][2]});int right_y = max({vec[0][1]-vec[0][3], vec[1][1]-vec[1][3], vec[2][1]-vec[2][3]});if (vec[0][0] >= (vec[1][0]+vec[1][2]) || (vec[0][0]+vec[0][2]) < vec[1][0]) { return 0;}int ans = (right_x - left_x) * ( left_y - right_y);cout << ans << endl;    return 0;
}56、 计算面积 
题解:
#include using namespace std;int main() {int N,E,X,offsetY,area,preX=0,curY=0;cin>>N>>E;for (int i=0; i>X>>offsetY;area += (X-preX)*curY;preX = X;curY += offsetY;}area += (E-preX)*curY;cout<using namespace std;int get_distance(vector& player, string& item) {int e1 = 0;int e2 = 0;for (int i = 0; i < 10; i++) {if (item.find(to_string(i)) != string::npos) {e1 += player[i];}else {e2 += player[i];}}return abs(e1 - e2);
}int main() {string input;getline(std::cin, input);vector player;size_t pos = 0;string token;while ((pos = input.find(" ")) != string::npos) {token = input.substr(0, pos);player.push_back(stoi(token));input.erase(0, pos + 1);}player.push_back(stoi(input));sort(player.begin(), player.end());string items = "0123456789";vector permutations;do {permutations.push_back(items.substr(0, 5));} while (next_permutation(items.begin(), items.end()));int min_d = INT_MAX;for (auto& item : permutations) {int d = get_distance(player, item);min_d = min(min_d, d);}cout << min_d << endl;return 0;
}58、 乱序整数序列两数之和绝对值最小 
题解:#include#include 
#include 
#include 
#include 
using namespace std;int main() {string str;getline(cin, str);stringstream ss(str);int temp;vector arr;int cursor = 0;while(ss >> temp) {if(temp < 0) {cursor++; //负数正数分界线}arr.push_back(temp);}sort(arr.begin(), arr.end());int len = arr.size();if(cursor == 0) {cout << arr[0] << " " << arr[1] << " " << arr[0] + arr[1] << endl;  // 全正数,头2个和最少} else if(cursor == len - 1) {cout << arr[len - 2] << " " << arr[len - 1] << " " << abs(arr[len - 1] + arr[len - 2]) << endl; //全负数,后2个和最少} else {  // 负数最大和正数最小  和的绝对值最小int positive = arr[cursor] + arr[cursor + 1]; //2个正数和int negative = abs(arr[cursor - 2] + arr[cursor - 1]);int result;vector output;if(negative < positive) {result = negative;output.push_back(arr[cursor - 2]);output.push_back(arr[cursor - 1]);output.push_back(negative);} else {result = positive;output.push_back(arr[cursor]);output.push_back(arr[cursor + 1]);output.push_back(positive);        }for(int i = 0; i < cursor; i++) {for(int j = cursor; j < len; j++) {int sumAbs = abs(arr[i] + arr[j]);if(sumAbs < result) {result = sumAbs;output.clear();output.push_back(arr[i]);output.push_back(arr[j]);output.push_back(sumAbs);}}}cout << output[0] <<  ' '  << output[1] <<  ' '  << output[2] << endl;}return 0;
}59、 流水线  、  流水线调度
题解:
#include
#include
#includeusing namespace std;int main(){// 输入处理int m, n;cin >> m >> n;vector tasks(n);for(int i = 0; i < n; i++) {cin >> tasks[i];}//排序sort(tasks.begin(), tasks.end());// 每条流水线的总耗时vector sum(m, 0);for (int i = 0; i < n; ++i) {sum[i % m] += tasks[i];}sort(sum.begin(), sum.end());cout << sum[m-1];return 0;
}60、 拼接URL   字符串处理
题解:
#include
#include
#include
#include
#includeusing namespace std;int main(){string str;getline(cin, str);if(str.size() == 1 && str == ",") {cout << '/' < vec;while(ss >> str) {vec.push_back(str);}cout << '/' << vec[0] << '/' << vec[1] << endl;return 0;
}61、  一种字符串压缩表示的解压 
题解:
#include
#include
#include
#include
#includeusing namespace std;int main(){string str;getline(cin, str);for(auto ch : str) {if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z')) {continue;} else {cout << "!error" << endl;return 0;}}int left = 0, right;string res;int index = 0;while(left < str.size()) {if(str[left] >= '1' && str[left] <= '9') {right = left + 1;while(str[right] >= '0' && str[right] <= '9')  {right++;}int count = stoi(str.substr(left, right - left));if(count == 2) {cout << "!error" << endl;return 0;} else {while(count--) {res += str[right];}}left = right + 1;}res += str[left++];}cout << res << endl;return 0;
}62、 转骰子
题解:
#include 
#include 
#include using namespace std;int main()
{string s = "123456";string input;getline(cin,input);int i = 0;while (i < input.size()){switch (input[i]){case 'L':{char temp1 = s[5];            char temp2 = s[1];char temp3 = s[4];char temp4 = s[0];s[5] = temp4;s[1] = temp1;            s[4] = temp2;s[0] = temp3;            break;}case 'R':{char temp1 = s[1];char temp2 = s[5];char temp3 = s[0];char temp4 = s[4];s[1] = temp4;s[5] = temp1;s[0] = temp2;s[4] = temp3;break;}case 'F':{char temp1 = s[2];char temp2 = s[5];char temp3 = s[3];char temp4 = s[4];s[2] = temp4;s[5] = temp1;s[3] = temp2;s[4] = temp3;break;}case 'B':{char temp1 = s[3];char temp2 = s[5];char temp3 = s[2];char temp4 = s[4];s[3] = temp4;s[5] = temp1;s[2] = temp2;s[4] = temp3;break;}case 'A':{char temp1 = s[1];char temp2 = s[3];char temp3 = s[0];char temp4 = s[2];s[1] = temp4;s[3] = temp1;s[0] = temp2;s[2] = temp3;break;}case 'C':{char temp1 = s[0];char temp2 = s[3];char temp3 = s[1];char temp4 = s[2];s[0] = temp4;s[3] = temp1;s[1] = temp2;s[2] = temp3;break;}}i++;}cout << s << endl;//system("pause");return 0;
}63、 数字涂色 
题解:
#includeusing namespace std;int main()
{int n;cin >> n;vector vec;int value;for(int i = 0; i < n; i++) {cin >> value;vec.push_back(value);}sort(vec.begin(), vec.end());int count = 0;if(vec[0] == 1) {count = 1;} else {vector ans(n, false);for(int i = 0; i < n; i++) {if(ans[i] == true) {continue;}for(int j = i; j < n; j++) {if(vec[j] % vec[i] == 0) {ans[j] = true;}}count++;}}cout << count << endl;return 0;
}64、 组成最大数 
题解:
#includeusing namespace std;bool cmp(string s1, string s2) {return s1 + s2 > s2 + s1;
}int main()
{string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');vector strs;stringstream ss(str);while(ss >> str) {strs.push_back(str);}sort(strs.begin(), strs.end(), cmp);string ans;for(int i = 0; i < strs.size(); i ++)ans += strs[i];cout << ans << endl;return 0;
}65、 寻找相同子串 
题解:
#includeusing namespace std;int main() {string t, p;getline(cin, t);getline(cin, p);char t_str[1000000];char p_str[10000];strcpy(t_str, t.c_str());strcpy(p_str, p.c_str());char *tmp = strstr(t_str,p_str);if(tmp == NULL) {cout << "NO" << endl;} else {cout << t.size()-strlen(tmp)+1 << endl;}return 0;
}66、  快递运输     贪心算法
题解:
#includeusing namespace std;int main() {string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');vector vec;stringstream ss(str);while(ss >> str) {vec.push_back(stoi(str));}int sum;cin >> sum;sort(vec.begin(), vec.end());int res = 0;for(auto val : vec) {sum -= val;if(sum <= 0) {cout << res;return 0;}res++;}return 0;
}67、  斗地主之顺子
题解:
#include 
#include 
#include 
#include 
#include 
#include using namespace std;int main() {// 处理输入string input_str;getline(cin, input_str);vector card_vec;stringstream ss(input_str);while(ss >> input_str) {if (input_str ==  "J") {card_vec.push_back(11);} else if (input_str ==  "Q") {card_vec.push_back(12);} else if (input_str ==  "K") {card_vec.push_back(13);} else if (input_str ==  "A"){card_vec.push_back(14);} else {card_vec.push_back(stoi(input_str));}}// 排序sort(card_vec.begin(), card_vec.end());set card_set(card_vec.begin(), card_vec.end());// 寻找顺子bool flag = false;   // 表示是否有满足要求的顺子int i = 0;while (i < card_vec.size() - 4) {vector tmp;tmp.push_back(to_string(card_vec[i]));for (int j = 1; j < card_vec.size(); j++) {if (i + j <= card_vec.size() - 1) {int value_i = card_vec[i];int value_ij = card_vec[i + j];if (value_i + j == value_ij) {if (value_ij == 11) {tmp.push_back("J");} else if (value_ij == 12) {tmp.push_back("Q");} else if (value_ij == 13) {tmp.push_back("K");} else if (value_ij == 14) {tmp.push_back("A");} else {tmp.push_back(to_string(value_ij));}} else {i += j;break;}} else {i += j;break;}}if (tmp.size() >= 5) {flag = true;for (int j = 0; j < tmp.size(); j++) {if (j != tmp.size() - 1) {cout << tmp[j] << " ";} else {cout << tmp[j] << endl;}}}}if (!flag) {cout << "No" << endl;}return 0;
}68、  英文输入法
题解:
#includeusing namespace std;int main(){string input_str;getline(cin, input_str);// 先按照空格分割set input_strs;stringstream ss(input_str);while(ss >> input_str) {input_strs.insert(input_str);}string target;getline(cin, target);bool find = false;vector v(input_strs.begin(), input_strs.end());for(int i = 0; i < v.size(); i++) {if ((v[i].find(target)) == 0) {cout << v[i] << " ";find = true;}}if(find == false) {cout << target << endl;}return 0;
}69、 数列描述     逻辑分析
题解:
#includeusing namespace std;string countAndSay(string result) {string res = "";int count = 1;char val = result[0];for (int i = 1; i < result.size(); i++) {if (result[i] == result[i - 1]) {count++;} else {res += to_string(count) + val;count = 1;val = result[i];}}res += to_string(count) + val;return res;
}int main(){int n;cin >> n;string result = "1";for(int i = 1; i <= n; i++) {result = countAndSay(result);}cout << result << endl;return 0;
}70、 分月饼
题解:
#includeusing namespace std;vector vec;int dispatch(int m, int n, int i) {// 不满足分配条件if (n <= 0 || m <= 0) {return 0; }if (m == 1) {if (n >= i && n <= i + 3) {return 1;}return 0;}int count = 0;//递归for (int j = i; j <= i+3; j++) {vec.push_back(j);count += dispatch(m-1, n-j, j);vec.pop_back();}return count;
}int main() {// 输入int m, n;cin >> m >> n;// 表示其他人都得到1个,剩下最后一个能拿到的最多月饼数n = n - m;int count = 0;// i 表示分到月饼最少的那个人得到的月饼数for (int i = 0; i <= n; i++) {vec.push_back(i);// 递归count += dispatch(m-1, n-i, i); vec.pop_back();}cout << count << endl;return 0;
}71、  日志排序
题解:
#include
#include
#include
#include
#includeusing namespace std;int get_millisecond(string time) {// 先按照冒号分割vector v;replace(time.begin(), time.end(), ':', ' ');replace(time.begin(), time.end(), '.', ' ');stringstream ss(time);while (ss >> time) {v.push_back(time);}    int hour = stoi(v[0]) * 60 * 60 * 1000;int minute = stoi(v[1]) * 60 * 1000;int second = stoi(v[2]) * 1000;int millisecond = stoi(v[3]);return hour + minute + second + millisecond;
}bool comp(pair a, pair b) {if (a.first < b.first) {return true;}return false;
}int main(){//输入处理string count_str;getline(cin, count_str);int count = stoi(count_str);vector times;for (int i=0;ivector> timestamps;for (auto x : times) {timestamps.push_back(make_pair(get_millisecond(x), x));}// 自定义排序sort(timestamps.begin(), timestamps.end(), comp);for(auto x : timestamps) {cout << x.second << endl;}return 0;
}72、  最长的指定瑕疵度的元音子串
题解:
#includeusing namespace std;int main() {//元音音符字典string aeiou = "aeiouAEIOU"; int flaw;cin >> flaw;string str;cin >> str;// idx是索引,maxLen是记录的最大长度,no_vowel是当前队列中已经保存了多少个非元音字符queue qe;int idx = 0, maxLen = -1, no_vowel = 0, templen = 0;while (idx < str.size()) {char tmp = str[idx];qe.push(tmp);//遇到非元音字符if (aeiou.find(tmp) == string::npos) {no_vowel++;}//如果入队列的是一个非元音字符,则与flaw比较。while (no_vowel > flaw && ! qe.empty()) {tmp = qe.front();// 如果删队首元素是一个非元音,则no_vowel--if (aeiou.find(tmp) == string::npos) {no_vowel--;}qe.pop();}templen = qe.size();maxLen = max(maxLen, templen);idx++;}// 找不到满足条件的元音字符子串,输出0if (no_vowel != flaw) {maxLen = 0;}cout << maxLen << endl;return 0;
}73、 查找众数及中位数
题解:
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int main()
{map colects;int n = 0;int maxNum = 0;while (cin>>n){if (colects.count(n)){colects[n]++;maxNum = max(maxNum, colects[n]);}else{colects[n] = 1;maxNum = max(maxNum, 1);}}vector middles;for (auto it = colects.begin(); it != colects.end(); it++){if (it->second == maxNum){middles.push_back(it->first);}}if (middles.size()%2){cout << middles[middles.size() / 2] << endl;}else{cout << (middles[middles.size() / 2 - 1] + middles[middles.size() / 2]) / 2 << endl;}return 0;
}74、 非严格递增连续数字序列 、 非严格递增序列
题解:
贪心:
#include 
#include 
#include 
#include using namespace std;int main()
{string str;cin >> str;if (str.size() == 0){cout << 0 << endl;return 0;}int maxlen = 1;int count = 1;for (int i = 0, j = 0; i < str.size(); i++) {if(str[i] >= '0' && str[i] <= '9') {j = i + 1;while((str[j] >= '0' && str[j] <= '9') && (str[j] >= str[j-1])) {j++;count++;}if(count > maxlen) {maxlen = count;}count = 1;i = j + 1;  }}cout << maxlen << endl;return 0;
}
或者dp:
#include 
#include 
#include 
#include using namespace std;int main()
{string str;cin >> str;if (str.size() == 0){cout << 0 << endl;return 0;}int maxlen = -1;for (int i = 0, j = 0; i < str.size(); i++) {if(str[i] >= '0' && str[i] <= '9') {j = i + 1;while(str[j] >= '0' && str[j] <= '9') {j++;}string temp = str.substr(i, j-i);vector dp(temp.size(), 1);for (int k = 1; k < temp.size(); k++) {if (temp[k] >= temp[k - 1]) { // 连续记录dp[k] = dp[k - 1] + 1;}if (dp[k] > maxlen) maxlen = dp[k];}i = j+1;}}cout << maxlen << endl;return 0;
}75、 考古学家  考古问题
题解:  dfs  回溯   全排列有重复
#include 
#include 
#include 
#include using namespace std;vector> res;
vector path;void dfs(vector& vec, vector used) {if(path.size() == vec.size()) {res.push_back(path);return;}for(int i = 0; i < vec.size(); i++) {if(i > 0 && vec[i] == vec[i - 1] && used[i-1] == false) {continue;}if(used[i] == false) {used[i] = true;path.push_back(vec[i]);dfs(vec, used);path.pop_back();used[i] = false;}}
}int main() {string input;getline(cin, input);int num = stoi(input);vector vec;while(cin >> input) {vec.push_back(input);}res.clear();path.clear();sort(vec.begin(), vec.end());vector used(num, false);dfs(vec, used);for(auto val : res) {string temp = "";for(auto x : val) {temp += x;}cout << temp << endl;}return 0;
}76、  水仙花数II(字符串分割)  
题解:  回溯和水仙花数    (整合 力扣 分割回文串 和 水仙花数)
#includeusing namespace std;vector> result;
vector path; bool isShuXian(const string& s, int start, int end) {int num = 0;for(int i = start; i <= end; i++) {char ch = s[i];num += int(ch);}// 必然是三位数if (num < 100 || num > 999) {return false;}int bai = num / 100;int shi = (num % 100) / 10;int ge = (num % 100) % 10;int v = pow(bai, 3) + pow(shi, 3) + pow(ge, 3);return v == num;
}void backtracking (const string& s, int startIndex) {// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了if (startIndex >= s.size()) {result.push_back(path);return;}for (int i = startIndex; i < s.size(); i++) {if (isShuXian(s, startIndex, i)) {// 是水仙花数// 获取[startIndex,i]在s中的子串string str = s.substr(startIndex, i - startIndex + 1);cout << str << endl;path.push_back(str);}  else {continue;}backtracking(s, i + 1); // 寻找i+1为起始位置的子串path.pop_back(); // 回溯过程,弹出本次已经添加的子串}
}int main()
{string str;cin >> str;if (str.size() > 200){cout << 0 << endl;return 0;}result.clear();path.clear();backtracking(str, 0);if(result.size() == 0) {cout << 0 < 1){cout << -1 <#define MAX_SIZE 100typedef struct AllocatedMemory {int hasAllocated[MAX_SIZE];
} AllocatedMemory;void initMemory(AllocatedMemory* memory) {for (int i = 0; i < MAX_SIZE; i++) {memory->hasAllocated[i] = 0;}
}char* requestMemory(AllocatedMemory* memory, int size) {int addressDefaultHead = 0;int addressHead = addressDefaultHead;if (size <= 0 || size > 100) {return "error";}bool hasAllocatedEmpty = true;for (int i = 0; i < MAX_SIZE; i++) {if (memory->hasAllocated[i] != 0) {hasAllocatedEmpty = false;break;}}if (hasAllocatedEmpty) {memory->hasAllocated[addressDefaultHead] = size;} else {int headList[MAX_SIZE];int headListLength = 0;for (int i = 0; i < MAX_SIZE; i++) {if (memory->hasAllocated[i] != 0) {headList[headListLength++] = i;}}for (int i = 0; i < headListLength; i++) {int integer = headList[i];if (integer - addressHead >= size) {memory->hasAllocated[addressHead] = addressHead + size;break;} else {addressHead = memory->hasAllocated[integer];}}int addressDefaultEnd = 100;if (size <= addressDefaultEnd - addressHead) {memory->hasAllocated[addressHead] = addressHead + size;} else {return "error";}}char* result = (char*)malloc(sizeof(char) * 10);sprintf(result, "%d", addressHead);return result;
}bool releaseMemory(AllocatedMemory* memory, int startAddress) {if (memory->hasAllocated[startAddress] != 0) {memory->hasAllocated[startAddress] = 0;return true;}return false;
}int main() {AllocatedMemory memory;initMemory(&memory);int line;scanf("%d", &line);getchar();char ins[line][2][10];for (int i = 0; i < line; i++) {scanf("%[^=]=%s", ins[i][0], ins[i][1]);getchar();if (strstr(ins[i][0], "REQUEST")) {printf("%s\n", requestMemory(&memory, atoi(ins[i][1])));} else {bool ret = releaseMemory(&memory, atoi(ins[i][1]));if (!ret) {printf("error\n");}}}return 0;
}78、 太阳能板最大面积
题解:
#includeusing namespace std;int main() {string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');stringstream ss(str);vector vec;while(ss >> str) {vec.push_back(stoi(str));}int i = 0;int j = vec.size()-1;int res = 0;while(i < j) {if(vec[i] < vec[j]) {i++;if(res < (j - i) *vec[i]) {res = (j - i) *vec[i];}} else {j--;if(res < (j - i) *vec[j]) {res = (j - i) *vec[j];}}}cout << res << endl;return 0;
}79、 N个小朋友分组
题解:
https://blog.csdn.net/weixin_45292794/article/details/11570151680、 字符串子序列II 判断字符串子序列 最后一个子序列的起始位置
题解:   双指针  字符串匹配
#includeusing namespace std;int main() {string target, source;cin >> target;cin >> source;int i = target.size() - 1;int j = source.size() - 1;while (i >= 0 && j >= 0) {	// 逆序逐字符遍历soueceif (target[i] == source[j]) {if(i == 0) {cout << j << endl;return 0;}i--;}j--;}cout << -1 << endl;return 0;
}81、 最小传输时延I   times[i] = (ui, vi, wi)
题解:
#includeusing namespace std;
int main()
{// 读入数据int n, m;cin >> n >> m;vector> times;for (int i = 0; i < m; i++) {int u, v, w;cin >> u >> v >> w;times.push_back({u, v, w});}int start, end;cin >> start >> end;vector>> graph(n + 1);// 构建图for (auto& time : times) {int u = time[0], v = time[1], w = time[2];graph[u].push_back({v, w});}// 初始化距离数组vector dist(n + 1, INT_MAX);dist[start] = 0;// 初始化待检查节点数组vector check_list;check_list.push_back(start);while (!check_list.empty()) {bool flag = false;int u = check_list[0];// 遍历相邻节点for (auto& next : graph[u]) {int v = next.first, w = next.second;int newDist = dist[u] + w;// 更新最短距离if (newDist >= dist[v]) continue;dist[v] = newDist;// 将新节点加入待检查数组if (find(check_list.begin(), check_list.end(), v) == check_list.end()) {check_list.push_back(v);flag = true;}}// 移除当前节点并按距离排序if (!flag) {check_list.erase(check_list.begin());}else {sort(check_list.begin(), check_list.end(), [&](int a, int b) { return dist[a] < dist[b]; });}}cout<<(dist[end] == INT_MAX ? -1 : dist[end]);return 0;
}82、 最小传输时延II   连续两个相同时延可以减少一个时延值 
题解:
#include 
#include 
#include 
#include 
#include using namespace std;int m, n; // 矩阵的行数和列数
vector> matrix; // 存储矩阵的二维向量
vector> offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; // 存储八个方向的偏移量void dfs(int i, int j, int delay, int last, unordered_set& path, vector& res) {int cur = matrix[i][j]; // 当前位置的值bool flag = cur == last; // 判断是否需要等待一秒if (i == m - 1 && j == n - 1) { // 到达终点delay += cur - (flag ? 1 : 0); // 更新延迟时间res.push_back(delay); // 将当前的延迟时间加入结果向量return;}for (auto& offset : offsets) { // 遍历八个方向int new_i = i + offset[0]; // 新的行坐标int new_j = j + offset[1]; // 新的列坐标int pos = new_i * n + new_j; // 将二维坐标转换为一维坐标if (new_i >= 0 && new_i < m && new_j >= 0 && new_j < n && !path.count(pos)) { // 判断新的位置是否越界且是否已经访问过path.insert(pos); // 将新的位置加入路径中dfs(new_i, new_j, delay + cur - (flag ? 1 : 0), cur, path, res); // 递归遍历新的位置path.erase(pos); // 将新的位置从路径中删除,回溯到上一步}}
}int main() {cin >> m >> n; // 输入矩阵的行数和列数matrix.resize(m, vector(n)); // 初始化矩阵的二维向量for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {cin >> matrix[i][j]; // 输入矩阵的每个元素}}vector res; // 存储所有到达终点的路径的延迟时间unordered_set path; // 存储当前路径中已经访问过的位置path.insert(0); // 将起点加入路径中dfs(0, 0, 0, INT_MAX, path, res); // 从起点开始遍历矩阵cout << *min_element(res.begin(), res.end()) << endl; // 输出所有到达终点的路径中的最小延迟时间return 0;
}83、  猴子爬山
题解:
#includeusing namespace std;int main() { int k, n;  long f[1000];cin >> n;f[1]=1;f[2]=1;f[3]=2;        // 数组元素赋初值  for(k=4;k<=n;k++)f[k]=f[k-1]+f[k-3];       // 按递推关系实施递推  cout << f[n] << endl;return 0;}84、 跳格子   、   跳格子游戏
题解:
#include
int methods(int n){if(n<3){return n;}else{return methods(n-1) + methods(n-2);}
}
using namespace std;
int main(){int n; // 格子数cin >> n;cout<
using namespace std;bool change_order_compare(string problem, string answer){sort(problem.begin(), problem.end());sort(answer.begin(), answer.end());if(answer == problem){return true;}return false;
}bool duplicate_compare(string problem, string answer){set problem_set;for(int i=0; i answer_set;for(int i=0; i inputstr() {string temp_str;vector temp;getline(cin, temp_str);replace(temp_str.begin(),temp_str.end(),',',' ');stringstream tempstr(temp_str);while(tempstr >> temp_str) {temp.push_back(temp_str);}return temp;
}int main()
{vector problems = inputstr();vector answers = inputstr();vector resList;for(int i = 0; i < problems.size(); i++) {string problem = problems[i];  bool flag = false; for(int j=0; j
using namespace std;int main()
{int n, m;cin >> n >> m;vector v;int temp;while(cin >> temp) {v.push_back(temp);if(cin.get() == '\n') {break;}}sort(v.begin(), v.end());//贪心选择int result = 0;//遍历给的木料长度,每次都补一下最短的木板,每次补完之后重新排序,重复此步骤。for (int i = 0; i < m; i++) {v[0] = v[0] + 1;sort(v.begin(), v.end());result = max(result, v[0]);}cout << result << endl;return 0;
}87、 查找 / 找出 重复代码
题解:
#includeusing namespace std;void findfun(string maxstr, string minstr) {string resstr = "";for(int i =0;i < minstr.length()-1; i++) {for(int j = i+2; j <= minstr.length(); j++) {string temp = minstr.substr(i,j);if(maxstr.find(temp) != string::npos && temp.length() > resstr.length()) {resstr = temp;}}}cout << resstr;
}int main()
{string str1, str2;getline(cin,str1);getline(cin,str2);int len =0;if(str1.size() > str2.size()) {findfun(str1,str2);} else {findfun(str2, str1);}return 0;
}或者dp:#includeusing namespace std;int main()
{string str1, str2;getline(cin,str1);getline(cin,str2);if(str1.size() > str2.size()) {swap(str1, str2);}int start = 0, max= 0;vector> dp(str1.size() + 1, vector(str2.size()+1, 0));for(int i = 1; i <= str1.size(); i++) {for(int j = 1; j <= str2.size(); j++) {if(str1[i-1] == str2[j-1]) {dp[i][j] = dp[i-1][j-1]+1;}if(dp[i][j] > max) {max = dp[i][j];start = i - max;}}}cout << str1.substr(start, max) << endl;return 0;
}88、  查找单入口空闲区域
题解:   根据岛屿面积加个非入口边界点置零的操作,把得到> 0 的面积和坐标统计
#includeusing namespace std;int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void dfs(vector>& grid, vector>& visited, int x, int y, bool flag, int* count) {if(!flag) {if (x == 0 || x == grid.size() - 1 || y == 0 || y == grid[0].size() - 1) {*count = 0;return;}}for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过if (!visited[nextx][nexty] && grid[nextx][nexty] == 'O') { // 没有访问过的 同时 是陆地的visited[nextx][nexty] = true;(*count)++;dfs(grid, visited, nextx, nexty, false, count);}}
}int main()
{//输入处理int m , n;cin >> m >> n;vector> matrix(m, vector(n));for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {cin >> matrix[i][j];}}//最大的区域大小  int maxArea = 0;vector> visited = vector>(m, vector(n, false));map zones;int count;for(int i = 0; i < m; i++){for(int j = 0; j < n; j++){if(!visited[i][j] && matrix[i][j] == 'O' && (i==0 || j==0 || i==m-1 || j==n-1)){//先假定当前可以为入口// count = 1;  // 因为dfs处理下一个节点,所以这里遇到陆地了就先计数,dfs处理接下来的相邻陆地visited[i][j] = true;count = 1;dfs(matrix, visited, i, j, true, &count);if (count > 0) {string key = to_string(i) + " " + to_string(j);zones[key]= count;if (count > maxArea) {maxArea = count;}}}}}//输出string max_entrace = "";for (auto it = zones.begin();it!=zones.end();it++) {if (it->second == maxArea) {if (max_entrace == "") {max_entrace = it->first;} else {max_entrace = "more";break;}}}if (maxArea == 0) {cout<<"NULL";} else if (max_entrace == "more") {cout << maxArea;} else {cout << max_entrace << " " << maxArea;}return 0;
}89、 单词倒序
题解:
符号也反转用这个:
#includeusing namespace std;int main()
{string temp;cin >> temp;reverse(temp.begin(), temp.end());cout << temp;while(cin >> temp) {cout << " ";reverse(temp.begin(), temp.end());cout << temp;}return 0;
}符号不反转用这个:
#includeusing namespace std;int main() {string str;getline(cin, str);string temp = "";string res = "";for(int i = 0; i < str.size(); i++) {char ch = str[i];if(ch >= 'a' && ch <= 'z') {temp += ch;} else if(ch == ' ') {res.append(temp.rbegin(), temp.rend());res += ' ';temp = "";} else {if(temp != "") {res.append(temp.rbegin(), temp.rend());temp = "";}res.append(1, ch);}if(i == str.size() -1 && temp != "") {res.append(temp.rbegin(), temp.rend());}}cout << res << endl;return 0;
}90、 对称字符串  对称美学
题解:
#include
using namespace std;int process(long count,long cur,int reverse) {if(count ==1) {return reverse;}long mid = count/2;if(cur < mid) {reverse++;return process(mid,cur,reverse);}else {return process(mid,cur-mid,reverse);}
}int main(){itn i;cin >> t;for(int i =0; i< t; i++) {int n,k;cin >> n >> k;long num = (long)pow(2,n-1);int color = process(num,k,0);if(color % 2 == 0) {cout << "red" << endl;} else {cout << "blue" << endl;}}return 0;
}91、 分界线 匿名信
题解:
#include
using namespace std;int main()
{string temp_str;vector> news;vector> anony;while(cin >> temp_str) {set temp(temp_str.begin(), temp_str.end());news.push_back(temp);if(cin.get() == '\n') {break;}}while(cin >> temp_str) {set temp(temp_str.begin(), temp_str.end());anony.push_back(temp);if(cin.get() == '\n') {break;}}for (auto x : anony) {if (find(news.begin(), news.end(), x) == news.end()) {cout << "false";return 0;}}cout << "true";return 0;
}92、 关联端口组合并   端口合并
题解:
#includeusing namespace std;bool check(set value1, set value2) {int count = 0;for (auto x : value1) {if (value2.count(x)) {count++;}if (count >= 2) {return true;}}return false;
}int main()
{int m;cin >> m;    // 限定范围if (m > 10 || m < 1) {cout<<"[[]]";return 0;}vector> vec;string temp;while(cin >> temp) {replace(temp.begin(), temp.end(), ',', ' ');set value;stringstream ss(temp);while(ss >> temp) {value.insert(stoi(temp));}vec.push_back(value);}for (int i = 0; i < vec.size(); i++) {for (int j = i + 1; j < vec.size(); j++) {if (check(vec[i], vec[j])) {//合并去重vec[i].insert(vec[j].begin(),vec[j].end());vec.erase(vec.begin() + j);}}}cout << "[";for(int i = 0; i < vec.size(); i++) {if(i) {cout << ',';}cout << '[';for(auto it = vec[i].begin(); it != vec[i].end(); it++) {if(it != vec[i].begin()) {cout << ',';}cout << (*it);}cout << ']';}cout << "]";return 0;
}93、 货币单位换算
题解:
#includeusing namespace std;double calculate(string numstr, char c);
double getValue(string str);int main() {int m;cin >> m;int res =0;string str;while(cin >> str) {res += getValue(str);}cout << res;return 0;
}double getValue(string str){string temp ="";double count =0;for(int i=0; i< str.length();i++) {char ch = str[i];if(isdigit(ch)) {temp += ch;} else {if(temp == "") {continue;}count += calculate(temp,ch);i+=2;temp = "";}}return count;
} double calculate(string numstr, char ch) {double count = 0;int num = stoi(numstr);if(ch == 'C') {count = num*100;} else if(ch == 'J') {count = num*10000/1825;} else if(ch == 'H') {count = num*10000/123;} else if(ch == 'E') {count = num*10000/14;} else if(ch == 'G') {count = num*10000/12;} else if(ch == 'f') {count = num*1;} else if(ch == 's') {count = num*100/1825;} else if(ch == 'c') {count = num*100/123;} else if(ch == 'e') {count = num*100/14;} else if(ch == 'p') {count = num*100/12;}return count;
}94、 获得 完美走位
题解:
//不确定直接算> 0的行不,可以试下
#includeusing namespace std;int main(){string input;getline(cin, input);map count;for(auto val : input){if(count.find(val) != count.end()) {count[val]++;} else {count[val] = 1;}}if(count['W'] == count['A'] &&count['W']== count['D'] &&count['W'] == count['S']) {cout << 0;return 0;}int len = input.size()/4;int res = 0;for(auto x : count) {x.second -= len;if(x.second > 0) {res += x.second;} }cout << res;return 0;
}或者:
#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;
int ans = 0;
string str;
int avg = 0;
int num[256] = { 0 };void dfs(int left, int right, int numTmp[256])
{if (right == left){return;}if (numTmp['W'] <= avg && numTmp['A'] <= avg && numTmp['S'] <= avg && numTmp['D'] <= avg){ans = ans > (right - left) ? (right - left) : ans;numTmp[str[left]]++;dfs(left + 1, right, numTmp);numTmp[str[left]]--;numTmp[str[right - 1]]++;dfs(left, right - 1, numTmp);numTmp[str[right - 1]]--;}else{return;}
}int main()
{int left = 0, right = 0;cin >> str;int numTmp[256] = { 0 };for (string::iterator it = str.begin(); it != str.end(); it++){num[*it]++;}avg = str.size() / 4;ans = str.size();left = 0, right = str.size();if (num['W'] == avg && num['A'] == avg && num['S'] == avg && num['D'] == avg){ans = 0;}else{dfs(left, right, numTmp);}cout << ans << endl;return 0;
}95、 简单的自动曝光
题解:
#include
using namespace std;
#include using namespace std;int main()
{int temp;vector nums;double sum = 0;while(cin >> temp) {nums.push_back(temp);sum += temp;}double aver = sum/nums.size()-128;int res = aver > 0 ? (int)(aver+0.5) : (int)(aver-0.5);int lesszeronum = 0, lesszero = 0;for(auto value : nums){if(value - res < 0) {lesszero += value - res;lesszeronum++;}} res -= lesszero /(nums.size() - lesszeronum);cout << 0-res;return 0;
}96、 日志采集系统  日志首次上报最多积分
题解: 
#include using namespace std;#define max(a,b) (((a) > (b)) ? (a) : (b))int delaysum(vector nums, int index){int delay = 0;for(int i =0; i  nums;while(cin >> temp) {nums.push_back(temp);}int len = nums.size();int sum = nums[0];int result = nums[0];if(sum >= 100) {cout << 100;return 0;} else {for(int i = 1; i < len; i++) {sum += nums[i];if(sum >= 100) {result = max(result, 100 - delaysum(nums,i));} else {result = max(result, sum - delaysum(nums,i));}}}cout << result << endl;return 0;
}97、  数组的中心位置  计算 数组中心位置
题解:
#includeusing namespace std;int main() {int temp;int sum = 1;vector vec;while(cin >> temp) {sum *= temp;vec.push_back(temp);if(cin.get() == '\n') {break;}}if(vec.size() == 1) {cout << 0;return 0;}int left = vec[0];    int res = -1;if(sum/vec[0] == 1) {res = 0;} else {for(int i = 1; i < vec.size(); i++) {sum /= vec[i-1];left *= vec[i];if(left == sum) {res =  i;}}}cout << res << endl;return 0;
}98、 通信误码
题解:
#includeusing namespace std;int main()
{int k;cin >> k;vector nums;    //定义哈希表和最大频数unordered_map mp;int maxcont = 0;int temp;while(cin >>temp) {nums.push_back(temp);if(mp.count(temp)) {mp[temp]++;            maxcont = max(maxcont, mp[temp]);} else {mp[temp] = 1;}}mp.erase(mp.begin(), mp.end());int res = nums.size();int left = 0, right =0;while(right < nums.size())  {mp[nums[right]]++;;while(mp[nums[right]] == maxcont) {res = min(res, right-left+1);mp[nums[left++]]--;}right++;}cout << res;return 0;
}99、   网上商城优惠活动
题解:
#includeusing namespace std;vector nums;pair funAB(int value);
pair funAC(int value);
pair funBA(int value);
pair funBC(int value);
bool cmp(pair a, pair b);int main() {int value;while(cin >> value) {nums.push_back(value);if(cin.get() == '\n') {break;}}int m;cin >> m;for(int i =0; i < m; i++) {cin >> value;vector> v;v.push_back(funAB(value));v.push_back(funAC(value));v.push_back(funBA(value));v.push_back(funBC(value));sort(v.begin(),v.end(), cmp);cout << v[0].first << " " << v[0].second << endl;}return 0;
}pair funAB(int value) {int resvalue = value;int acount = resvalue /100;int count = 0;if(acount > nums[0]) {resvalue -= 10*nums[0];count = nums[0];} else {resvalue -= 10*acount;count = acount;}if(nums[1] > 0) {resvalue = (int)(resvalue*0.92);count += 1;}return make_pair(resvalue, count);
}pair funAC(int value) {int resvalue = value;int acount = resvalue /100;int count = 0;if(acount > nums[0]) {resvalue -= 10*nums[0];count = nums[0];} else {resvalue -= 10*acount;count = acount;}resvalue -= 5*nums[2];count += nums[2];return make_pair(resvalue, count);
}pair funBA(int value) {int resvalue = 0;int count = 0;if(nums[1] > 0) {resvalue =  (int)(value*0.92);count += 1;}int acount = resvalue /100;if(acount > nums[0]) {resvalue -= 10*nums[0];count += nums[0];} else {resvalue -= 10*acount;count += acount;}return make_pair(resvalue, count);
}pair funBC(int value) {int resvalue = 0;int count = 0;if(nums[1] > 0) {resvalue =  (int)(value*0.92);count += 1;}resvalue -= 5*nums[2];count += nums[2];return make_pair(resvalue, count);
}bool cmp(pair a, pair b) {if (a.first > b.first) {return false;} else if (a.first == b.first){return a.second > b.second;}return true;
}100、  获取最大软件版本号
题解:
#includeusing namespace std;//逐个比较即可
bool comp(vector a, vector b) {if (a[0] == b[0]) {if (a[1] == b[1]) {if (a[2] == b[2]) {return a[3] > b[3];} else {return a[2] > b[2];}} else {return a[1] > b[1];}} else {return a[0] > b[0];}
}vector inputVersion(string version){vector versioninfo;replace(version.begin(),version.end(),'-',' ');replace(version.begin(),version.end(),'.',' ');stringstream tempstr(version);while(tempstr >> version) {versioninfo.push_back(version);}return versioninfo;
}int main()
{//输入处理string version1;string version2;getline(cin, version1);vector version1Info = inputVersion(version1);getline(cin, version2);vector version2Info = inputVersion(version2);if (comp(version1Info, version2Info)) {cout << version1 << endl;} else {cout << version2 << endl;}return 0;
}101、   寻找链表的中间结点
题解:
#includeusing namespace std;typedef struct ListNode{int value;int next;ListNode(int value,int next){this->value = value;this->next = next;}
};int main()
{int paddr,n;cin >> paddr >> n;int addr,value,next;unordered_map mp;for(int i =0; i < n; i++) {cin >> addr >> value >> next;mp[addr] = new ListNode(value, next);}// 构造链表ListNode* head = mp[paddr];    /* 快慢指针法 */ListNode* fast = head;ListNode* slow = head;// 快指针每次走两步,慢指针每次走一步while (fast->next != -1 && mp[fast->next]->next != -1) {fast = mp[mp[fast->next]->next];slow = mp[slow->next];}// 处理偶数个结点的情况if (fast->next != -1) {slow = mp[slow->next];}// 输出结果cout << slow->value;return 0;
}102、 字符串解密
题解:
#includeusing namespace std;int main() {string str1, str2;cin >> str1 >> str2;set str2diff(str2.begin(), str2.end());int str2len = str2diff.size();for(int i = 0; i < str1.size(); i++) {if((str1[i] >= 'a' && str1[i] <= 'f')  || (str1[i] >= '0' && str1[i] <= '9') ) {str1[i] = ' ';}}stringstream ss(str1);int maxlen = 0;string temp = "";while(ss >> str1) {set str1diff(str1.begin(), str1.end());int str1len = str1diff.size();if(str1len <= str2len) {if(str1len > maxlen) {temp = str1;maxlen = str1len;} else if(str1len == maxlen && str1 > temp) {temp = str1;}}}if(temp.size() == 0) {cout << "Not Found";} else {cout << temp;}return 0;
}103、   投篮大赛
题解:
#includeusing namespace std;int main()
{string str;getline(cin, str);stringstream ss(str);vector operas;while(ss >> str) {operas.push_back(str);}vector scores;for (int i=0;iusing namespace std;int main()
{string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');stringstream ss(str);vector nums;while(ss >> str) {nums.push_back(stoi(str));}if(nums.back() == 0) {cout << "[]" << endl;return 0;}int prenum = 0;cout << '[';for(int i = nums.back(); i >= 0; i--) {int temp = nums[0]*i + nums[1]*(nums.back()-i);if(temp != prenum) {if(i < nums.back()) {cout << ',';}cout << temp;prenum = temp;}}cout << ']' << endl;return 0;
}105、 找数字  找等值元素
题解:
#includeusing namespace std;int main()
{int n, m;cin >> n >> m;vector> vec(n, vector(m));map>> mp;for(int i = 0; i < n; i++) {for(int j = 0; j < m; j++) {cin >> vec[i][j];mp[vec[i][j]].push_back(pair(i, j));}}vector> res(n, vector(m));for(int i = 0; i < n; i++) {for(int j = 0; j < m; j++) {vector> numMp(mp[vec[i][j]]);if(numMp.size() == 1) {res[i][j] = -1;continue;}int min = INT_MAX;for(int k = 0; k < numMp.size(); k++) {int dis = abs(numMp[k].first - i) + abs(numMp[k].second - j);if(dis == 0) {continue;}min = min < dis ? min : dis;}res[i][j] = min;}}cout << '[';for(int i = 0; i < n; i++) {if(i) {cout << ',';}cout << '[';for(int j = 0; j < m; j++) {if(j) {cout << ',';}cout << res[i][j];}cout << ']';}cout << ']' << endl;return 0;
}106、  箱子之型摆放   箱子之字形摆放
题解:
#includeusing namespace std;int main()
{string str;int num;cin >> str >> num;map mp;for(int i = 0; i < str.size(); i++) {int index;if(i/num%2 == 0) {index = i%num;} else {index = num - 1 - i%num;}mp[index].append(1, str[i]);}for(auto temp : mp) {cout << temp.second << endl;}return 0;
}107、   异常的打卡记录
题解:
#includeusing namespace std;int main(){int num;cin >>num;string input;vector> vec;while(num--) {cin >> input;replace(input.begin(), input.end(), ',', ' ');stringstream ss(input);vector value;while(ss >> input) {value.push_back(input);}vec.push_back(value);}//判断距离和时间int key = 0;for(int k = 0; k < vec.size(); k++) {//输出异常打卡数据if(vec[k][3] != vec[k][4]) {cout << vec[k][0] << ',' << vec[k][1] << ',' << vec[k][2] << ','  << vec[k][3]  << ',' << vec[k][4] << endl;key = 1;} else {for(int m = 0; m < vec.size(); m++) {if((vec[k][0] == vec[m][0]) && (abs(stoi(vec[k][1]) - stoi(vec[m][1])) < 60) && (abs(stoi(vec[k][1]) - stoi(vec[m][1])) > 5)) {cout << vec[k][0] << ',' << vec[k][1] << ',' << vec[k][2] << ','  << vec[k][3]  << ',' << vec[k][4] << endl;key = 1;} else {continue;}}}}if(key == 0) {cout << "null";}return 0;
}108、  相同数字的积木游戏1
题解:
#includeusing namespace std;int main() {int N = 0;int max = -1;cin >> N;map numbMap;for (int i = 0; i < N; ++i) {int a = 0;cin >> a;if (numbMap.count(a)) {max = max > (i - numbMap[a]) ? max : i - numbMap[a];} else {numbMap[a] = i;}}cout << max << endl;return 0;
}109、 学校的位置
题解:  中位数  数学题
#includeusing namespace std;int main() {int n;cin >> n;vector nums(n);for(int i =0; i < n; i++) {cin >> nums[i];}sort(nums.begin(), nums.end()); if(n%2) {cout << nums[(n-1)/2] << endl;} else {cout << nums[n/2] << endl;} return 0;
}110、  最长的密码   寻找密码  真正的密码
题解:
#include 
#include 
#include 
#include 
#include 
#include using namespace std;int main() {string input;getline(cin, input);stringstream ss(input);// 将所有字符串放入哈希集合set wordSet;while (ss >> input) {wordSet.insert(input);}// 真正的密码string res = "";//按顺序检查每一个词for (auto s : wordSet) {// 条件1:检查这个词所有以索引0开头的子串在数组中是否都有bool flag = true;for(int i = 1; i < wordSet.size(); i++){// 以索引0开头的子串string subStr = s.substr(0, i);if(!wordSet.count(subStr)){flag=false;break;}}if(flag){// 条件2:比较密码长度if(s.size() > res.size())res = s;// 条件3:比较密码字典排序if(s.size() == res.size()&& s > res){res = s;}}}cout << res;return 0;
}111、  磁盘容量   、 磁盘容量排序
题解:
#includeusing namespace std;int getValue(string str){string temp ="";int count =0;for(int i = 0; i < str.length();i++) {char ch = str[i];if(isdigit(ch)) {temp += ch;} else {if(ch == 'M') {count += stoi(temp);} else if(ch == 'G') {count += stoi(temp)*1024;} else {count += stoi(temp)*1024*1024;}temp = "";}}return count;
}int cmp(string a, string b) {int numa = getValue(a);int numb = getValue(b);return numa < numb;
}int main() {int n;cin >> n;vector vec;for(int i = 0; i < n ; i++) {string input;cin >> input;vec.push_back(input);}sort(vec.begin(), vec.end(), cmp);for(auto str : vec) {cout << str << endl;}return 0;
}112、  跳格子2    力扣原题 213   
题解: dp
#includeusing namespace std;int robRange(vector& nums, int start, int end) {if (end == start) {return nums[start];   }vector dp(nums.size());dp[start] = nums[start];dp[start + 1] = max(nums[start], nums[start + 1]);for (int i = start + 2; i <= end; i++) {dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);}return dp[end];
}int main() {int num;vector nums;while(cin >> num) {nums.push_back(num);}int res;if(nums.size() == 0) {res = 0;} else if(nums.size() == 1) {res = nums[0];} else {int leftres = robRange(nums, 0, nums.size() - 2); int rightres = robRange(nums, 1, nums.size() - 1); res = max(leftres, rightres);}cout << res << endl;return 0;
}113、 解压报文  、  报文解压缩  、  压缩报文还原
题解: 输入带[]
#include 
#include 
#include using namespace std;int main() {string s;getline(cin, s);string ans = "";for (int i = 0; i < s.length(); i++) {if (s[i] == ']') {string tmp_s = "";while (!ans.empty()) {char ch = ans.back();ans.pop_back();if (isalpha(ch)) {tmp_s = ch + tmp_s;} else if (isdigit(ch)) {string num(1, ch);while (!ans.empty() && isdigit(ans.back())) {num = ans.back() + num;ans.pop_back();}string wait_s = tmp_s;for (int j = 1; j < stoi(num); j++) {tmp_s += wait_s;}}}ans += tmp_s;} else {ans.push_back(s[i]);}}cout << ans << endl;return 0;
}114、  简单的解压缩算法 
题解:   输入带{}  
#include 
#include 
#include 
#include 
#include using namespace std;void translate(string &cache, int pos,int cnt) {}int main() {string str;getline(cin,str);int n=str.size();string digit;string cache;vector bracket_postion;for(int i=0;iusing namespace std;int main() {int l, r;cin >> l >> r;int count = 0;for(int i = l; i <= r; i++) {bitset<10> bit(i);string str(bit.to_string());if(str.find("101") == string::npos) {count++;}}cout << count << endl;return 0;
}116、  最左侧冗余覆盖子串
题解:
#include using namespace std;bool check(string s1, string s2) {int count = 0;for(int i = 0; i < s1.size(); i++) {for(int j = 0; j < s2.size(); j++) {if(s1[i] == s2[j]) {s2[j] = ' ';count++;break;}}}return count == s1.size();
}
int main() {string str1, str2;getline(cin, str1);getline(cin, str2);int k;cin >> k;int res = -1;int strLen = str1.size() + k;for(int i =0; i < str2.size(); i++) {string str = str2.substr(i, strLen);if(check(str1, str)) {res = i;break;}}cout << res << endl;return 0;
}117、 最多提取子串数目
题解:
#include using namespace std;int main() {string strF, strS;getline(cin, strF);getline(cin, strS);int res = 0;int indexF = 0;int indexS = 0;while(indexF < strF.size()) {if(strF[indexF] == strS[indexS]) {strF[indexF] = ' ';indexS++;}if(indexS == strS.size()) {res++;indexS = 0;indexF = 0;} else {indexF++;}}cout << res <using namespace std;int main() {vector nums;int num;while(cin >> num) {nums.push_back(num);if(cin.get() == '\n') {break;}}cin >> num;int res = 0;for(int i = 0; i < nums.size() - num + 1; i++) {int count[3] = {0};for(int j = 0; j < num; j++) {count[nums[i+j]]++;}int maxcount = max(max(count[0], count[1]), count[2]);res = max(res, maxcount);}cout << res << endl;return 0;
}119、 优秀学员统计
题解:
#include using namespace std;int cmp(pair> a, pair> b) {if(a.second[0] == b.second[0]) {if(a.second[1] == b.second[1]) {return a.first < b.first;}return a.second[1] < b.second[1];}return a.second[0] > b.second[0];
}int main() {int n;cin >> n;int dayIn[30] = {0};for(int i = 0; i < 30 ; i++) {cin >> dayIn[i];}map> mp;for(int i = 0; i < 30; i++) {for(int j = 0; j < dayIn[i]; j++){int input;cin >> input;if(input > n-1) {continue;}if(mp.count(input) != 0) {mp[input][0]++;} else {mp[input] = vector {1, i};}}}vector>> vec(mp.begin(), mp.end());sort(vec.begin(), vec.end(), cmp);for(int i = 0; i < (vec.size() < 5 ? vec.size() : 5); i++) {cout << vec[i].first << ' ';}return 0;
}120、 租车骑绿道  租车骑绿岛
题解:
#include using namespace std;int main() {int m, n;cin >> m >> n;vector nums(n);for(int i = 0; i < n; i++) {cin >> nums[i];}sort(nums.rbegin(), nums.rend());int count = 0;for(int i = 0; i < n; i++) {if(nums[i] == 0) {continue;}if(nums[i] == m) {count++;} else {for(int j = i; j < n; j++) {if(nums[j] + nums[i] <= m) {count++;nums[j] = 0;break;}}}}cout << count << endl;return 0;
}122、   密室逃生游戏   寻找关键钥匙
题解:
#include using namespace std;int main() {string str1;getline(cin, str1);sort(str1.begin(), str1.end());string str2;getline(cin, str2);stringstream ss(str2);int res = -1, index = 1;while(ss >> str2) {string temp = "";for(int i = 0; i < str2.size(); i++) {if(str2[i] >= 'a' && str2[i] <= 'z') {temp += str2[i];} else if(str2[i] >= 'A' && str2[i] <= 'Z') {temp += str2[i] + 32;} }sort(temp.begin(), temp.end());if(str1 == temp) {res = index;}index++;}cout << res << endl;return 0;
}123、取出尽量少的球   开放日活动
题解:
#include using namespace std;int main() {long sum;int n;cin >> sum >> n;vector nums(n);long curSum = 0;long maxCap = 0;for(int i = 0; i < n; i++) {cin >> nums[i];maxCap = max(maxCap, nums[i]);curSum += nums[i];}if(curSum <= sum) {cout << "[]" << endl;return 0;}long left = sum/n;long right = maxCap;while(right > left) {long mid = left + (right-left)/2;long total = 0;for(int j = 0; j < n; j++) {total += min(mid, nums[j]);}if(total <= sum) {left = mid;} else{right = mid - 1;}}cout << '[';for(int k = 0; k < n; k++) {if(k) {cout << ',';}cout << (nums[k] - left > 0 ? nums[k] - left : 0);}cout << ']';return 0;
}124、 不开心的小朋友
题解:
#include using namespace std;int main() {int line[201] = {0};int flag[101] = {0};int emptyCar = 0;int count = 0;cin >> emptyCar;while(cin >> line[count++]) {if(cin.get() == '\n') {break;}}for(int i = 0; i < count; i++) {if(flag[line[i]] == 0) {if(emptyCar > 0) {emptyCar--;flag[line[i]] = 1;} else {flag[line[i]] = 2;}} else if(flag[line[i]] == 1){flag[line[i]] = 3;emptyCar++;} else {if(emptyCar > 0) {flag[line[i]] = 3;} else {flag[line[i]] = 2;}}}int res = 0;for(auto val : flag) {if(val == 2) {res++;}}cout << res << endl;return 0;
}125、  最小循环子数组
题解: KMP算法
#include 
#include 
#include 
#include 
#include using namespace std;int main() {int n;cin >> n;vector nums(n);int i = 0;while(cin >> nums[i++]) {if(cin.get() == '\n') {break;}}int next[n] = {0};int j = -1;for(i = 1; i < n; i++) {if(nums[i] != nums[j+1]) {j = next[j+1];} else {j++;}next[i] = j;}int len = (n % (n - (next[n-1] + 1)) == 0 ? n - (next[n-1] + 1): n);for(i = 0; i < len; i++){cout << nums[i] << ' ';}return 0;
}126、 矩阵元素的边界值   矩阵元素边界值
题解:
#include 
#include 
#include 
#include 
#include 
#include using namespace std;int main() {string input;getline(cin, input);input.erase(0, 1);input.erase(input.size()-1, 1);vector> vec;for(int i = 0; i < input.size(); i++) {if(input[i] == '[') {int j = i + 1;while(input[j] != ']') {j++;}string temp = input.substr(i+1, j-i-1);stringstream ss(temp);vector value;while(getline(ss, temp, ',')) {value.push_back(stoi(temp));}vec.push_back(value);}}int res;int find = 0;for(int i = 0; i < vec[0].size(); i++) {find = vec[0][i];for(int j = 1; j < vec.size(); j++) {find = max(find, vec[j][i]);}if(i == 0) {res = find;} else {res = min(res, find);}}cout << res << endl;return 0;
}127、    数字反转打印 、 数字的排列
题解:
#include 
using namespace std;void print(int num) {cout << num;if (num < 10) { cout << "***"; }else if (num < 100) { cout << "**"; }else if (num < 1000) { cout << "*"; }
}void space(int i, int n) {int num = (n - i - 1);for (i = 0; i < num; ++i) {cout << "    ";}
}int main() {int n; // [1, 30]cin >> n;int start = 1;bool reverse = false;for (int i = 0; i < n; ++i) {space(i, n);// 第i行int end = start + i;if (reverse) {for (int j = end; j >= start; --j) {if (j != end) { cout << "    "; }print(j);}} else {for (int j = start; j <= end; ++j) {if (j != start) { cout << "    "; }print(j);}}reverse = !reverse;cout << endl;start = end + 1;}return 0;
}128、  比赛的冠亚季军
题解:
#include 
#include 
#include using namespace std;#define ll long longconst int maxn = 1e4+10;
int n;
ll a[maxn];
int winnumber,losenumber;struct node{int id;ll value;
}win[maxn],lose[maxn];int main(){while(scanf("%lld",&a[n++])!=EOF);n--;winnumber=n;losenumber=0;// 所有人都进胜者组,开始一轮比赛 for(int i = 0; i < n; ++i){win[i] = (node){i,a[i]};}bool flag = false;// 一直比赛,直到胜者组只剩一人,也就是冠军,而最后一个进败者组的就是亚军 while(winnumber > 1){// 空间复用,将胜者组依旧记录在胜者组 int tmp = winnumber;winnumber = 0;for(int i = 0; i < tmp-1; i += 2){if(win[i].value > win[i+1].value || (win[i].value == win[i+1].value && win[i].id < win[i+1].id)){// 实力胜或者实力相等编号小 lose[losenumber++]=win[i+1];win[winnumber++]=win[i];}else if(win[i].value < win[i+1].value){// 实力败 lose[losenumber++]=win[i];win[winnumber++]=win[i+1];}}if(tmp&1) // 奇数情况最后一个人直接获胜 win[winnumber++]=win[tmp-1];if(tmp == 4)// 记录最后是四人半决赛还是三人半决赛 flag = true;}// 冠亚军确定 printf("%d %d ", win[0].id, lose[losenumber-1].id);if(!flag){// 三人半决赛,季军确定 printf("%d", lose[losenumber-2].id);}else{// 四人半决赛,败者组再战 if(lose[losenumber-2].value > lose[losenumber-3].value || (lose[losenumber-2].value == lose[losenumber-3].value && lose[losenumber-2].id < lose[losenumber-3].id)){printf("%d", lose[losenumber-2].id);}else{printf("%d", lose[losenumber-3].id);}}return 0;
}129、 恢复数字序列
题解:
#include 
#include 
#include 
#include using namespace std;int asciiSum(const string& s) {int sum = 0;for (char c : s) {sum += c - '0';}return sum;
}string generateSequence(int startNum, int len) {string sequence;for (int i = 0; i < len; i++) {sequence += to_string(startNum + i);}//cout << "sequence is  " << sequence << endl;return sequence;
}int main() {string input;int len;cin >> input >> len;sort(input.begin(), input.end());//cout << "input is  " << input << endl;int totalSum = asciiSum(input);//cout << "totalSum is " << totalSum << endl;int minNumLen = input.length() / len;int minNum = -1;int j = 0;while(j < input.length()-minNumLen) {string temp = input.substr(j, minNumLen - 1);for (int i = 0; i <= 9; i++) {string candidate = temp + to_string(i);    //cout << "candidate is  " << candidate << endl;int num = stoi(candidate);int tmpnum = asciiSum(generateSequence(num, len));//cout << "tmpnum is " << tmpnum << endl;if (tmpnum == totalSum) {minNum = num;cout << minNum << endl;return 0;}}j += minNumLen;}return 0;
}130、 荒岛求生
题解:
#include
#include
#includeusing namespace std;int main() {int temp;vector vec;while(cin >> temp) {vec.push_back(temp);if(cin.get() == '\n') {break;}}//栈中存放的都是往右跑的人,往左跑的已经被打败,或者逃生成功stackst;int idx = 0;int ans = 0;while(idx < vec.size()) {//栈中全是往右跑的人,当idx对应的人往左跑while (!st.empty() && idx < vec.size() && vec[idx] < 0 ){int a = st.top();st.pop();if (abs(a) > abs(vec[idx])) {a -= vec[idx];idx++;st.push(a);} else if (abs(a) < abs(vec[idx])) {vec[idx] += abs(a);}// abs这块和加减可以调}//如果往左逃生的人前面没有往右逃生的人,则往左逃生的人逃生成功if (idx < vec.size() && st.empty() && vec[idx] < 0) {ans++;} else if(idx < vec.size()) {st.push(vec[idx]);}idx++;}cout << ans + st.size() << endl;return 0;
}131、  找最小数 、 最小数字   移除 K 位数字的最小值
题解:  2615371 移除4位变 131 最小   单调栈的思想(力扣 402 移除k位数字)
#include 
#include 
#include 
#include using namespace std;int main() {// 处理输入string num;getline(cin, num);int n;cin >> n;string ans;for (int i = 0; i < num.length(); i++) {while (n > 0 && !ans.empty() && ans.back() > num[i]) {ans.pop_back();n -= 1;}if (ans.size() == 0 && num[i] == '0'){continue;}ans += num[i];}while (n > 0 && !ans.empty()){ans.pop_back();n--;}if(ans.size() == 0) {cout << "0" << endl;} else {cout << ans <
#include 
#include 
#include using namespace std;int main () {// Part Istring t;int n = 0;vector one, two, three, four, five, vec, ans;while (cin >> n) {t = to_string(n);if (t.size() == 1) one.push_back(t);else if (t.size() == 2) two.push_back(t);else if (t.size() == 3) three.push_back(t);else if (t.size() == 4) four.push_back(t);else five.push_back(t);if (cin.get() == '\n') break;}sort(one.begin(), one.end());sort(two.begin(), two.end());sort(three.begin(), three.end());sort(four.begin(), four.end());// Part IIfor (int i = 0; i < one.size(); i++) vec.push_back(one[i]);for (int i = 0; i < two.size(); i++) vec.push_back(two[i]);for (int i = 0; i < three.size(); i++) vec.push_back(three[i]);for (int i = 0; i < four.size(); i++) vec.push_back(four[i]);for (int i = 0; i < five.size(); i++) vec.push_back(five[i]);for (int i = 0; i < vec.size(); i++) {if (i > 2) break;ans.push_back(vec[i]);}sort(ans.begin(), ans.end());for(auto val : ans) {cout << val;}t.clear();return 0;
}132、  增强的strstr
题解:   dfs 回溯
#include  
using namespace std;vector res;void dfs(vector vec, int ind, string ans){if(ind == vec.size()){//cout << ans << endl;res.push_back(ans);return;}for(int i = 0; i < vec[ind].size(); i++){ans += vec[ind][i];dfs(vec, ind+1, ans);ans.pop_back();}
}int main(){string base, tar;cin >> base >> tar;int n = tar.size();vector vec;for(int i = 0; i < n; i++){if(isalpha(tar[i])) {string t = "";vec.push_back(t+tar[i]);//cout << vec.back() << endl;}else if(tar[i]='['){string tmp="";while(tar[i]!=']'){if(isalpha(tar[i])){tmp += tar[i];}i++;}vec.push_back(tmp);//cout << vec.back() << endl;}}string tmp;dfs(vec, 0, tmp);int low = base.size();int pos;for(int i = 0;i < res.size(); i++){if((pos = base.find(res[i])) != base.npos){low = min(low, pos);}}cout << low << endl;return 0;
}或者 正则:
#include  
using namespace std;int main()
{string haystack, needle;cin >> haystack >> needle;regex re(needle);smatch match;if (regex_search(haystack, match, re)){cout << match.position() << endl;}else{cout << -1 << endl;}return 0;
}133、 最大广播响应 、  最长广播响应
题解:  计算BFS层数的问题
#includeusing namespace std;int main() {int n, t;cin >> n >> t;// 节点之间一定是互联互通的,不要单向传播不到int u, v;map> mp; //记录边到边的关系for (int i = 0; i < t; ++i) {cin >> u >> v;mp[u].insert(v);mp[v].insert(u);}int start;cin >> start;queue que;set visited;int cnt = 0; // 记录几层能够遍历完成que.push(start);visited.count(start);while (visited.size() < n){ // 当全部感染完成了int size = que.size();for (int i = 0; i < size; ++i) {auto cur = que.front();que.pop();for(auto next : mp[cur]){if(visited.count(next) == 0){ // 之前没有走过visited.insert(next);que.push(next);}}}cnt++;}cout << cnt * 2 << endl;return 0;
}134、  字符串加密   str[i]偏移特定数组元素a[i]的量
题解:  字符串处理  注意取余
#includeusing namespace std;int main() {int n;cin >> n;cin.ignore();vector vec(n);for(int i = 0; i < n; i++) {getline(cin, vec[i]);}string all = "abcdefghijklmnopqrstuvwxyz";for(int i = 0; i < n; i++) {vector pianyi({1, 2, 4});string res;for(int j = 0; j < vec[i].size(); j++) {if(j < 3) {int index = (all.find(vec[i][j]) + pianyi[j]) % 26;res += all[index];}  else {pianyi.push_back(pianyi[j - 1] + pianyi[j - 2] + pianyi[j - 3]);int index = (all.find(vec[i][j]) + pianyi[j]) % 26;res += all[index];}}cout << res << endl;}return 0;
}135、   数据分类
题解: 对一个数据a进行分类 a 累加用int("01",16),转化为十进制累加 % b  < c , 有效类型组多的个数   位运算
// Online C++ compiler to run C++ program online
#include
#include
#include
#include
#includeusing namespace std;int main(){// 处理输入int c, b;cin >> c >> b;map mp;for(int i = 0; i < 10; ++i) {int num;cin >> num;int sum = 0;while(num > 0) {sum += num & 0xff;num >>= 8;}int res = sum % b;if(res < c) {if(!mp.count(res)) {mp[res] = 1;}else {mp[res]++;}}}int res = 0;for(auto x : mp) {res = max(res, x.second);}cout << res;return 0;
}136、  基于身高差排序
题解: 身高差绝对值从小到大排序#include 
#include 
#include using namespace std;int cmp(pair a, pair b){if(a.second == b.second) {return a.first < b. first;} else {return a.second < b.second;}
}int main(){int H, N;//身高--学生个数cin >> H >> N;cin.ignore();vector arr(N);vector> diff;for(int i = 0; i < N; i++){cin >> arr[i];diff.push_back({i, abs(arr[i] - H)});}sort(diff.begin(), diff.end(), cmp);for(auto val : diff){cout << arr[val.first] << " ";}return 0;
}137、   最大花费 、 双十一   、   最大花费金额
题解: 回溯,和 查找充电设备组合   类似
#include 
#include 
#include 
#include 
#include using namespace std;int ans = 0;
int cnt;void dfs(vector& value, int psum, int target, int index) {if(cnt == 3) {if(target <= psum) {ans = max(ans,target);}return;}for(int i = index; i < value.size(); i++) {if(psum - value[i] >= 0) {cnt++;target += value[i];dfs(value, psum, target, i+1);target -= value[i];cnt--;}}
}int main() {int summax;vector value;while(cin >> summax) {value.push_back(summax);if(cin.get() == '\n') {break;}}cin >> summax;sort(value.begin(), value.end());if(value.size() < 3 || (value[0] + value[1] + value[2] > summax)){cout << "-1";return 0;}cnt = 0;dfs(value, summax, 0, 0);if(ans) {cout << ans << endl;} else {cout << "-1" << endl;}return 0;
}138、  找字符   、  找出符合要求的字符串子串  
题解:  从字符串2中找出字符串1中的所有字符,去重并按照ASCII码值从小到大排列
#include
#includeusing namespace std;int main()
{string str1;string str2;getline(cin, str1);getline(cin, str2);int ch[26] = {0};for(int i = 0; i < str2.size(); i++){for(int j = 0; j < str1.size(); j++){if(str1[j] == str2[i]){ch[str2[i]-'a'] = 1;}}}for(int i = 0; i < 26; i++){if(ch[i] == 1){cout <<  char(i + 'a');}}return 0;
}139、 相同数字组成图形的周长
题解: 思维 + 遍历  问题转化为求每个有颜色的格子,其上下左右四个相邻格子与其颜色不相等的颜色数量。
#include 
using namespace std;int dis[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};int main()
{int m;cin >> m;cin.ignore();int n = 64;vector> grid(n, vector(n));vector nums;for(int i = 0; i < m; i++) {vector vec;int value;while(cin >> value) {vec.push_back(value);if(cin.get() == '\n') {break;}}nums.push_back(vec[0]);for (int j = 1; j + 1 < vec.size(); j += 2) {// 给对应的格子赋值grid[vec[j]][vec[j + 1]] = vec[0];}}// 统计每个值的周长之和map val;for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j)// 当一个格子有值,才可能有边长if (grid[i][j] > 0) {int res = 4;for(int k = 0; k < 4; k++) {int nextx = i + dis[k][0];int nexty = j + dis[k][1];if (nextx >= 0 && nextx < n && nexty >= 0 && nexty < n && grid[nextx][nexty] == grid[i][j]) {res -= 1;}}val[grid[i][j]] += res;}for (int i = 0; i < m; ++i) {cout << val[nums[i]] << " \n"[i + 1 == m];   /*" \n"[i == n - 1]:表示一个字符数组,根据i是否等于n-1来选择输出空格或换行符。当i等于n-1时," \n"[i == n - 1]相当于" \n"[1],输出换行符;否则," \n"[i == n - 1]相当于" \n"[0],输出空格。 */}return 0;
}140、   敏感字段加密
题解:  遍历和标志位思想
#include 
#include 
#include 
using namespace std;int main()
{int n = 0;cin >> n;string str;cin >> str;string tmp;vector vec;bool bInMark = false; // 引号中的'_'符号不作为结束标志,跳过for (int i = 0; i < str.size(); i++) {if (str[i] != '_') {tmp += str[i];if (str[i] == '\"') {bInMark = !bInMark;}} else {if (!tmp.empty() && !bInMark) {vec.push_back(tmp);tmp.clear();}}if (i == str.size() - 1 && !tmp.empty()) {vec.push_back(tmp);tmp.clear();}}if (n > vec.size()){cout << "ERROR" << endl;} else {for (int i = 0; i < vec.size(); i++) {if (i) {cout << "_";}if (i == n) {cout << "******";} else {cout << vec[i];}}}cout << endl;return 0;
}141、 人气最高店铺  、 人气最高的店铺
题解:
#includeusing namespace std;int money = 0;
int result = INT_MAX;int cmp(pair a, pair b) {return a.second > b.second;
}bool check(vector>& changePeoples, map shopInfo){map newShopInfo = shopInfo;money = 0;for(auto ints : changePeoples){int shopId = ints[0];money += ints[1];// 人气调换newShopInfo[shopId] -= 1;newShopInfo[1] += 1;}vector> shopList(newShopInfo.begin(), newShopInfo.end());// 降序排序sort(shopList.begin(), shopList.end(), cmp);// 人气第一的店铺int top1Id = shopList[0].first;if(top1Id == 1 && (shopList.size() == 1 || cmp(shopList[0], shopList[1]))){return true;}return false;
}void backfill(vector>& peoples, vector>& changePeoples, int index, map& shopInfo){// 判断此时一号店铺是否是第一名,且所需要的钱最少if(check(changePeoples, shopInfo) && result > money){result = money;}else {// 组合求解for(int i = index; i < peoples.size(); i++){changePeoples.push_back(peoples[i]);backfill(peoples, changePeoples, i+1,shopInfo);changePeoples.pop_back();}}}vector getvalue(){string input;vector value;getline(cin, input);replace(input.begin(), input.end(), ',', ' ');stringstream ss(input);while(ss >> input) {value.push_back(stoi(input));}return value;
} int main()
{vector value = getvalue();// 初始化商店和投票人vector> peoples;map shopInfo;shopInfo[1] = 0;for(int i = 0; i < value[0]; i++){vector peoplesValue = getvalue();if(peoplesValue[0] != 1){peoples.push_back(peoplesValue);}if (shopInfo.count(peoplesValue[0])) {shopInfo[peoplesValue[0]] += 1;} else {shopInfo[peoplesValue[0]] = 1;}}vector> temp;backfill(peoples, temp, 0, shopInfo);cout << result;return 0;
}143、  阿里巴巴找黄金宝箱  (III) 
题解: 第一对相等且距离小于n的起始位置
#includeusing namespace std;int main() {vector nums;string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');stringstream ss(str);while(ss >> str) {nums.push_back(stoi(str));}getline(cin, str);int n = stoi(str);map mp;for (int i = 0; i < nums.size(); i++) {if (!mp.count(nums[i])) {mp[nums[i]] = i;} else {if((i - mp[nums[i]]) <= n) {cout << mp[nums[i]];return 0;}}}cout << "-1" ;return 0;
}144、  阿里巴巴找黄金宝箱  (IV) 
题解:   下一个更大的元素      nums.size()*2   坐标  i%nums.size()的妙招
#include 
using namespace std;
int main(){int tmp;vector nums;while(cin >> tmp){nums.push_back(tmp);if(cin.get()=='\n') break;}vector result(nums.size(), -1);stack st;for (int i = 0; i < nums.size() * 2; i++) {// 模拟遍历两边nums,注意一下都是用i % nums.size()来操作while (!st.empty() && nums[i % nums.size()] > nums[st.top()]) {result[st.top()] = nums[i % nums.size()];st.pop();}st.push(i % nums.size());}for(int i = 0; i < result.size(); i++) {cout << result[i] << ",\n"[i+1==result.size()];}return 0;
}145、  阿里巴巴找黄金宝箱  (V) 
题解: 连续k个和的最大值    力扣原题 2461 : 长度为k子数组中的最大和
#include using namespace std;int main() {int tmp;vector vec;int sum = 0;while(cin >> tmp) {vec.push_back(tmp);if(cin.get() == '\n') break;}int k;cin >> k;int left = 0;int res = INT_MIN;for(int i = 0; i < vec.size(); i++) {sum += vec[i];if(i - left + 1 == k){res = max(res,sum);sum -= vec[left++];}}cout<
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;bool cmp(pair a, pair b){if(a.second == b.second){return a.first < b.first;}else{return a.second > b.second;}
}int main() {string input;cin >> input;int left = 0;int res = 0;//存最长长度string str;for(int i = 0;i < input.size(); i++) {if(isalpha(input[i])){str += tolower(input[i]);}}vector> vec;for(int i = 0; i < str.size(); i++){if(str[i] != str[left]){vec.push_back({str[left], i-left});left = i;}else if(i == str.size()-1){vec.push_back({str[left], i-left+1});}}sort(vec.begin(),vec.end(), cmp);for(auto v : vec){cout << v.first << v.second;}cout << endl;return 0;
}147、  目录删除  、 删除指定目录  、  树形目录删除
题解:  map 存父子关系   删除指定点  递归删除子节点的子节点
#includeusing namespace std;map> mp;void delFload(int id) {// 无子节点if(mp[id].size()) {for (int i = 0; i < mp[id].size(); i++) {delFload(mp[id][i]);}}mp.erase(id);
}int main() {// 输入int m;cin >> m;//构造父子关系for (int i = 0; i < m; i++) {int a, b;cin >> a >> b;if (mp.find(a) == mp.end()) {mp[a] = {};}if (mp.find(b) != mp.end()) {mp[b].push_back(a);} else {mp[b] = {a};}}// 删元素int d;cin >> d;delFload(d);for (auto val : mp) {if (val.first == 0) {continue;}cout << val.first << " ";}return 0;
}148、  删除有序数组中的重复项
题解: 双指针    力扣原题  26  删除有序数组中的重复项
输入set处理
#includeusing namespace std;int main() {// 输入int temp;set nums;while(cin >> temp) {if(nums.find(temp) == nums.end()) {nums.insert(temp);}if(cin.get() == '\n') {break;}}cout << nums.size();return 0;
}
或者双指针:
#includeusing namespace std;int main() {// 输入int temp;vector nums;while(cin >> temp) {nums.push_back(temp);if(cin.get() == '\n') {break;}}if (nums.size() == 0) {cout << nums.size();return 0;}int fast = 1, slow = 1;while (fast < nums.size()) {if (nums[fast] != nums[fast - 1]) {nums[slow] = nums[fast];++slow;}++fast;}cout << slow;return 0;
}149、  座位调整  、  调座
题解:   疫情课堂座位    逻辑分析
#include 
#include 
#include 
#include 
#include using namespace std;int main() {vector nums;nums.push_back(0);string str;getline(cin, str);replace(str.begin(), str.end(), ',', ' ');stringstream ss(str);while(ss >> str) {nums.push_back(stoi(str));}nums.push_back(0);int res = 0;int n = nums.size();for (int i = 1; i < nums.size()-1; i++) {if (nums[i] == 0) {if (i > 0 && nums[i - 1] == 0 && nums[i + 1] == 0) {nums[i] = 1;res++;}}}cout << res << endl;return 0;
}150、  经典屏保
题解:  log反弹t秒后坐标
#include 
#include using namespace std;int main() {int x, y, t;cin >> x >> y >> t;x = (x + t) % 1500;y = (y + t) % 1150;x = x > 750 ? 1500 - x : x;y = y > 575 ? 1150 - y : y;cout << x << ' ' << y << endl;return 0;
}或者:
#include 
#include 
#include 
#include 
#include using namespace std;int main() {int x, y, t;cin >> x >> y >> t;int xDir = 1, yDir = 1;int width = 800, height = 600;for(int i = 0; i < t; i++){if(x == 0){//碰到最左侧,y轴方向开始向右xDir = 1;}if(y == 0){//碰到最上层,x轴方向开始向下yDir = 1;}if(x + 50 == width){//碰到最右侧,x轴方向开始向左xDir = -1;}if(y + 25 == height){//碰到最下端,y轴方向向上yDir = -1;}x += xDir;y += yDir;}cout << x << ' ' << y << endl;return 0;
}151、  求符合条件元组个数  、  符合要求的元组的个数   、  k数之和
题解:
回溯解法:
#include using namespace std;vector> result;
vector path;
vector nums;
int k, target;
set ans;void backtrack(int start, vector& path) {if(path.size() == k && accumulate(path.begin(), path.end(), 0) == target) {result.push_back(path);return;}for(int i = start; i < nums.size(); i++) {if(ans.find(nums[i]) == ans.end()) {ans.insert(nums[i]);path.push_back(nums[i]);backtrack(i+1, path);path.pop_back();ans.erase(nums[i]);}}
}int main() {while(cin >> k) {nums.push_back(k);if(cin.get() == '\n') {break;}}cin >> k;cin.ignore();cin >> target;result.clear();path.clear();backtrack(0, path);cout << result.size();return 0;
}
或者双指针sort排序完先取前k-2个值,然后双指针找剩下2个:
#include using namespace std;int twoSum(vector nums, int target, int start, int result, long pre_sum) {int l = start;int r = nums.size() - 1;while (l < r) {long sum = pre_sum + nums[l] + nums[r];if (target < sum) {r--;} else if (target > sum) {l++;} else {result++;while (l + 1 < r && nums[l] == nums[l + 1]) l++;while (r - 1 > l && nums[r] == nums[r - 1]) r--;l++;r--;}}return result;
}int kSum(vector nums, int k, int target, int start, int result, long sum) {if (k < 2) {return result;}// 特殊情况if (k == 2) {return twoSum(nums, target, start, result, sum);}for (int i = start; i <= nums.size() - k; i++) {// 特殊情况直接退出if (nums[i] > 0 && sum + nums[i] > target) {break;}if (i > start && nums[i] == nums[i - 1]) {continue;}result = kSum(nums, k - 1, target, i + 1, result, sum + nums[i]);}return result;
}int main() {while(cin >> k) {nums.push_back(k);if(cin.get() == '\n') {break;}}cin >> k;cin.ignore();cin >> target;sort(nums.begin(), nums.end());cout<using namespace std;int main() {int tmp;vector vec;int sum = 0;while(cin >> tmp) {vec.push_back(tmp);if(cin.get() == '\n') break;}int k;cin >> k;int res = 0;for(int i = 0; i < vec.size(); i++) {int sum = 0;for(int j = i; j >= 0; j--) {sum += vec[j];if(sum == k){res++;}}}cout << res << endl;return 0;
}153、  最长公共后缀
题解:
#include 
#include 
#include using namespace std;int main() {string input;getline(cin, input); // 读入字符串数组input = input.substr(1, input.size() - 2); // 去除首尾的方括号vector vec;string temp = "";for (char c : input) {if (c == ',') { // 遇到逗号,将temp加入strArrvec.push_back(temp);temp = "";} else if (c != '\"') { // 去除双引号temp += c;}}vec.push_back(temp); // 将最后一个字符串加入strArrstring common = vec[0]; // 初始化公共后缀为第一个字符串for (int i = 1; i < vec.size(); i++) {int len1 = common.size();int len2 = vec[i].size();int j = 1;// 从后往前比较,找到第一个不同的字符位置jwhile (len1 - j >= 0 && len2 - j >= 0 && common[len1 - j] == vec[i][len2 - j]) {j++;}if (j == 1) { // 如果j=1,说明不存在公共后缀cout << "@Zero" << endl;return 0;}common = common.substr(len1 - j + 1); // 更新公共后缀}cout << common << endl;return 0;
}154、  食堂供餐
题解:
#include using namespace std;bool checkFun(vector vec, int mid, int m) {bool res = true;for(int i = 0; i <= vec.size(); i++){m -= vec[i];if(m < 0){res  = false;break;}m += mid;}return res;
}int main(){int n, m;cin >> n >> m;vector vec(n);int sum = 0;for(int i = 0; i < n; i++){cin >> vec[i];sum += vec[i];}int res = 0;int minnum = 0;int maxnum = sum - m;while(minnum < maxnum) {int mid = minnum + (maxnum - minnum)/2;if(checkFun(vec, mid, m)) {maxnum = mid;} else {minnum = mid + 1; }}cout << minnum << endl;return 0;
}155、  AI 识别面板
题解:
#includeusing namespace std;int cmp1(vectora, vectorb) {return a[2] - b[2];
}int cmp2(vectora, vectorb) {return a[1] - b[1];
}int main(){int n;cin >> n;vector> vec;for (int i = 0; i < n; i++) {int id, x1, y1, x2, y2;cin >> id >> x1 >> y1 >> x2 >> y2;vec.push_back({id, x1, y1, x2, y2});}// 纵坐标排序sort(vec.begin(), vec.end(), cmp1);int pos = 0;for(int i = 1; i < n; i++) {if((vec[i][2] - vec[pos][2]) <= (vec[pos][4] - vec[pos][2])/2) {continue;}sort(vec.begin()+pos, vec.begin()+i, cmp2);pos = i;}sort(vec.begin()+pos, vec.end(), cmp2);for(int i = 0; i < n; i++) {cout << vec[i][0] << " \n"[i+1 == n]; }return 0;
}156、  服务依赖   、    服务失效判断
题解:  和 目录删除  类似#includeusing namespace std;map> mp;void delFload(string id) {// 无子节点if(mp[id].size()) {for (int i = 0; i < mp[id].size(); i++) {delFload(mp[id][i]);}}mp.erase(id);
}vector inputSolution(string input, char ch) {vector result;replace(input.begin(), input.end(), ch, ' ');stringstream ss(input);while(ss >> input) {result.push_back(input);}return result;
} int main() {// 输入string input;getline(cin, input);vector value = inputSolution(input, ',');//构造父子关系for (int i = 0; i < value.size(); i++) {string temp = value[i];vector idVal = inputSolution(temp, '-');if (mp.find(idVal[0]) == mp.end()) {mp[idVal[0]] = {};}if (mp.find(idVal[1]) != mp.end()) {mp[idVal[1]].push_back(idVal[0]);} else {mp[idVal[1]] = {idVal[0]};}}// 删元素getline(cin, input);vector delvalue = inputSolution(input, ',');for(int i = 0; i < delvalue.size(); i++) {delFload(delvalue[i]);}if(mp.size() == 0) {cout << ',' <using namespace std;bool checkFun(char c1, char c2, char c3, char c4) {if (c4 != 'e') {return false;}if (!isalpha(c1)) {return false;}string vowel("aeiou");string vowel1("aeiour");if (vowel.find(c2) == vowel.npos)return false;if (vowel.find(c1) != vowel.npos)return false;if (vowel1.find(c3) != vowel1.npos)return false;return 'a' <= c3 && c3 <= 'z';    
}bool isAlpha(string str) {for(auto ch : str) {if(!isalpha(ch)) {return false;}}return true;
}int findKYY (string str) {if(str.length() < 4) {return 0;}int val = 0;if(!isAlpha(str)) {for(int i = 0; i <= str.length() - 4; i++) {if(checkFun(str[i], str[i+1], str[i+2], str[i+3])) {val++;}}} else {for(int i = str.length()-1; i > 2; i--) {if(checkFun(str[i], str[i-1], str[i-2], str[i-3])) {val++;}}}return val;
}int main() {string str;while(getline(cin, str)) {int res = 0;vector vec;stringstream ss(str);while(ss >> str) {vec.push_back(str);}for(auto val : vec) {res += findKYY(val);}cout << res;}return 0;
}158、 宜居星球改造计划
题解: BFS
#includeusing namespace std;int main() {vector> matrix;string line;while (getline(cin, line)) {if (line.size() == 0){break;} else {stringstream ss(line);vector value;while(ss >> line) {value.push_back(line);}matrix.push_back(value);}}int row = matrix.size();int col = matrix[0].size();// 记录宜居取坐标位置queue> que;// 记录可改造区数量int need = 0;for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if (matrix[i][j] == "YES") {que.push({i, j});} else if (matrix[i][j] == "NO") {need += 1;}}}// 如果没有宜居区,则无法改造,直接返回-1if (que.empty()) {return -1;}// 如果全是宜居区,则无需改造,直接返回0else if (que.size() == row * col) {return 0;}// 记录花费的天数int day = 0;// 上,下,左,右四个方向的偏移量vector> offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};// 图的多源BFS模板while (!que.empty() && need > 0) {queue> newQueue;while (!que.empty()) {pair coordinates = que.front();que.pop();int x = coordinates.first;int y = coordinates.second;for (auto& offset : offsets) {// 上,下,左,右四个方向扩散int newX = x + offset.first;int newY = y + offset.second;// 如果新位置没有越界,且为NO,则可以被改造if (newX >= 0 && newX < row && newY >= 0 && newY < col && matrix[newX][newY] == "NO") {matrix[newX][newY] = "YES";newQueue.push({newX, newY});need -= 1;}}}day += 1;que = newQueue;}if (need == 0) {cout << day << endl;} else {cout << "-1" << endl;}return 0;
}159、  查字典
题解:
#include 
#include 
#include using namespace std;int main() {string tmp;vector vec;while(cin >> tmp) {vec.push_back(tmp);if(cin.get() == '\n') {break;}}string prestr = vec[0];int flag = 0;for(int i = 2; i < vec.size(); i++) {if(vec[i].find(prestr) == 0){flag = 1;cout << vec[i] << endl;}}if(!flag) {cout << -1 << endl;}return 0;
}160、 TLV编码  、   TLV解析  I
题解:   字符处理 和 大小端 
#include 
#include 
#include using namespace std;
// 小端序(Small-Endian):低地址存放低字节,高地址存放高字节;
// 大端序(Big-Endian):高地址存放低字节,低地址存放高字节;
// 网络字节序使用大端法
// 32 位 int 强转 char数组,查看 0 ~ 3 的 打印可以判断大小端
int main() {// 处理输入string tagStr, tlvStr;getline(cin, tagStr);getline(cin, tlvStr);//空格分割vector list;tlvStr += " ";while (tlvStr.find(" ") != tlvStr.npos) {int found = tlvStr.find(" ");list.push_back(tlvStr.substr(0, found));tlvStr = tlvStr.substr(found + 1);}for (int i = 0; i < list.size(); ) {string tag = list[i];int length = stoi(list[i + 2] + list[i + 1], 0, 16);if (tag != tagStr) {i = i + 2 + length + 1;continue;}for (int j = 0; j < length; j++) {cout << list[i + 2 + j + 1 ] << " ";}break;}return 0;
}161、 TLV编码  、   TLV解析  II
题解:  没有空格  找长度和偏移量
#include
#include
#include
#include
#include
using namespace std;int main(){string msg;int n;cin >> msg >> n;vector tags(n);for (int i = 0; i < n; i++) {cin >> tags[i];}// 定义哈希表,存储tag对应的length和valueOffsetunordered_map> tagMap;// 解析msg,填充哈希表for (int i = 0; i + 3 < msg.length(); i++) {// 获取tag和len,将16进制字符串转换为整数int tag = stoi(msg.substr(i, 2), nullptr, 16);int len = stoi(msg.substr(i + 2, 2), nullptr, 16);// 计算valueOffsetint valueOffset = (i + 5) / 2;// 跳过value,更新ii += 3 + len * 2;// 如果i超出msg长度,跳出循环if (i >= msg.length()) {break;}// 将tag、length、valueOffset存入哈希表中tagMap[tag] = {len, valueOffset};}// 遍历tags,输出匹配结果for (auto tag : tags) {if (tagMap.count(tag)) {vector tmp = tagMap[tag];int len = tmp[0];int valueOffset = tmp[1];cout << len << " " << valueOffset << endl;} else {cout << "0 0" << endl;}}return 0;
}162、  书籍叠放
题解:
//先依据长度升序,再依据宽度降序的方式,对书本数组books进行排序
//然后求最长递增子序列
#include using namespace std;int main() {// 处理输入string input;getline(cin, input);input.erase(0, 1);input.erase(input.size()-1, 1);vector> vec;for(int i = 0; i < input.size(); i++) {if(input[i] == '[') {int j = i + 1;while(input[j] != ']') {j++;}string temp = input.substr(i+1, j-i-1);stringstream ss(temp);vector value;while(getline(ss, temp, ',')) {value.push_back(stoi(temp));}vec.push_back(value);}}sort(vec.begin(), vec.end());// 定义dp数组vector dp(vec.size(), 1);// 动态规划int ans = 1;for (int i = 1; i < vec.size(); i++) {for (int j = 0; j < i; j++) {if (vec[i][0] > vec[j][0] && vec[i][1] > vec[j][1]) {dp[i] = max(dp[i], dp[j] + 1);}}ans = max(ans, dp[i]);}cout << ans << endl;return 0;    
}163、   最小交换次数  最少交换次数
题解:   一个数组内 交换小于target的在一起
#includeusing namespace std;int main() {vector nums;int k;while(cin >> k) {nums.push_back(k);if(cin.get() == '\n') {break;}}cin >> k;int count = 0;for(auto val : nums) {count += (val < k ? 1 : 0);}int res = INT_MAX;for(int i = 0; i < nums.size() - count + 1; i++) {int temp = 0;for(int j = 0; j <  count; j++) {temp += (nums[i+j] > k ? 1 : 0);}res = min(res, temp);}cout << res;return 0;
}164、  使序列递增的最小交换次数   
题解:   2个数组进行交换
#includeusing namespace std;int main() {vector nums1;vector nums2;int value;while(cin >> value) {nums1.push_back(value);if(cin.get() == '\n') {break;}} while(cin >> value) {nums2.push_back(value);if(cin.get() == '\n') {break;}} int n = nums1.size();int resa = 0, resb = 1;for (int i = 1; i < n; i++) {int temp1 = resa, temp2 = resb;resa = resb = n;if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1])  {resa = min(resa, temp1);resb = min(resb, temp2 + 1);}if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) {resa = min(resa, temp2);resb = min(resb, temp1 + 1);}}cout << min(resa, resb) << endl;return 0;
}165、  分糖果    I
题解:  小明分糖果  
#includeusing namespace std;int dfs(int n) {if(n == 0 || n == 1) {return 0;}if(n%2 == 0) {return dfs(n/2)+1;} else {return min(dfs(n+1), dfs(n-1))+1;}
}int main() {int num;cin >> num;int res = dfs(num);cout << res;return 0;
}166、  分糖果   II
题解:   Solo 和  koko 两兄弟分  和分苹果一样   异或为0 ,和减去最小
#includeusing namespace std;int main(){int num;cin >> num;vector nums;int sum = 0;int tmp = 0;int minnum = 100001;while(cin >> num) {nums.push_back(num);tmp ^= num;sum += num;minnum = min(minnum, num);if(cin.get() == '\n') {break;}}if(tmp == 0) {cout << sum - minnum << endl;} else {cout << -1 << endl;}return 0;
}167、  分糖果     III均分
题解: 回溯  老师给小张和小王均分  力扣原题  40 、 组合总和II
//再背包问题的基础上,增加一个记录当前节点的满足条件的list
#includeusing namespace std;vector> result;
vector path;void backtracking(vector& vec, int target, int sum, int startIndex) {if (sum == target) {result.push_back(path);return;}for (int i = startIndex; i < vec.size() && sum + vec[i] <= target; i++) {// 要对同一树层使用过的元素进行跳过if (i > startIndex && vec[i] == vec[i - 1]) {continue;}sum += vec[i];path.push_back(vec[i]);backtracking(vec, target, sum, i + 1); // 和39.组合总和的区别1,这里是i+1,每个数字在每个组合中只能使用一次sum -= vec[i];path.pop_back();}
}void combinationSum2(vector& vec, int target) {path.clear();result.clear();// 首先把给candidates排序,让其相同的元素都挨在一起。sort(vec.begin(), vec.end());backtracking(vec, target, 0, 0);return;
}int main() {int m;cin >> m;vector vec(m);int sum = 0;for(int i = 0; i < m; i++) {cin >> vec[i];sum += vec[i];}if(sum%2 == 1) {cout << "-1" << endl;return 0;}int target = sum/2;combinationSum2(vec, target);if(result.size() == 0) {cout << "-1" << endl;} else {cout << target << endl;for(int i = 0; i < result.size(); i++) {if(i) {cout << endl;}for(int j = 0; j < result[i].size(); j++) {if(j) {cout << ' ';}cout << result[i][j];}}}return 0;
}168、   老师 分糖果   
题解:  多少个学生,分了多少等份
#includeusing namespace std;int main()
{int n;/*设老师共将糖果分成n等份*/float sum1, sum2;/*第1个和第2个学生得到的份数分别为sum1和sum2,可能是小数*/for(n = 11;  ; n++)/*糖果份数至少为11份时,第1个学生得到的才是完整的份数*/{sum1 = (n+9) / 10.0;//sum1=1+(n-1)/10sum2 = (9*n + 171) / 100.0;//sum2=2+(n-sum1-2)/10if(sum1 != (int)sum1) {/*最终得到的应该是整份数,sum1和sum2应为整数*/continue;}if(sum2 != (int)sum2) {continue;}if(sum1 == sum2) {break;}}cout << (int)(n/sum1) <<  "  "  << n << endl;return 0;
}169、   Alice 吃糖果
题解: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。
#includeusing namespace std;int main() {string str;getline(cin, str);str = str.substr(1, str.size()-2);stringstream ss(str);set mp; int size = 0;while(getline(ss, str, ',')) {mp.insert(str);size++;}int count = mp.size();cout << min(size/2, count) << endl;return 0;
}170、 分糖果   
题解:   同时把自己的糖果分一半给右边的人, 多少轮相等
#includeusing namespace std;int a[10], c[10];void dd() {for(int t = 0; t < 10; t++) {c[t] = a[t]/2;}for(int t = 0; t < 10; t++){a[t] += c[(t+9)%10] - a[t]/2;if(a[t]%2 == 1) {a[t]++;//补成偶数}}
}bool flag() {//判断糖果数是否相等for(int t = 1; t < 10; t++){if(a[t] != a[0]) {return false;}}return true;
}int main()
{for(int t = 0; t < 10; t++) {cin >> a[t];}int k = 0;while(1) {if(flag() == 1) {break;//完成}dd();//调整k++;//记录调整次数}cout << k << " " << a[0];
}171、   分积木
题解: 和  分苹果 一样  , 异或为0 ,和减去最小
#includeusing namespace std;int main(){int num;cin >> num;vector nums;int sum = 0;int tmp = 0;int minnum = 100001;while(cin >> num) {nums.push_back(num);tmp ^= num;sum += num;minnum = min(minnum, num);if(cin.get() == '\n') {break;}}if(tmp == 0) {cout << sum - minnum << endl;} else {cout << -1 << endl;}return 0;
}172、 稀疏矩阵     、   矩阵稀疏扫描
题解:  行/列 0的个数大于  (行/列)/2
#include using namespace std;int main() {int m, n;cin >> m >> n;vector> arr(m, vector (n));vector row(m,0);vector col(n,0);for(int i=0;i> arr[i][j];if(arr[i][j]==0){row[i]++;col[j]++;}}}int r = 0, c = 0;for(int i = 0; i < m; i++){if(row[i] > n/2){r++;}}for(int i = 0; i < n; i++){if(col[i] > m/2){c++;}}cout << r << endl;cout << c << endl;return 0;
}173、  叠积木   I
题解:    力扣 698 划分为k个相等的子集 变形。
//数量和长度不超过5000   (叠积木 II  数量和长度不超过50)
#includeusing namespace std;bool dfs(vector &nums, vector &res, int index, int target){if(index == nums.size()){return true;}for(int i = 0; i < res.size(); i++){if(res[i] + nums[index] > target){continue;}if(i > 0 && res[i] == res[i-1]){continue;}res[i] += nums[index];if(dfs(nums, res, index + 1, target)){return true;}res[i] -= nums[index]; }return false;
}int main() {vector nums;int temp;int sum = 0;while(cin >> temp) {nums.push_back(temp);sum += temp;if(cin.get() == '\n') {break;}}sort(nums.begin(), nums.end());int minnum = nums[0];int maxnum = nums[nums.size()-1];int flag = 1;for(int i = minnum; i <= sum/2; i++) {if(sum % i == 0) {int len = sum/i;vector res(len, 0);if(dfs(nums, res, 0, i)) {cout << len << endl;flag = 0;break;}}}if(flag){cout << "-1" << endl;}return 0;
}174、   响应报文时间
题解:  IGMP协议     位运算
//当MaxRespCode < 128,MaxRespTime = MaxRespCode;
//当MaxRespCode >= 128,MaxRespTime = (amnt | 0x10) << (exp + 3);
#include using namespace std;int getTime(int m) {if(m < 128) {return m;} else {int mant=(m & 0x0F);int exp=(m  & 0x70) >> 4;int res=(mant | 0x10) << (exp+3);return res;}
}int main() {int c;cin >> c;int maxtime = INT_MAX;for(int i = 0; i < c; i++){int t, m;cin >> t >> m;maxtime = min(maxtime, t + getTime(m));}cout << maxtime << endl;return 0; 
}175、   最大相连男生数 、  学生方阵
题解:
#include using namespace std;int bfs(vector> vec, int x, int y, int k, int maxcount) {if(x < 0 || x >= vec.size() || y < 0 || y >= vec[0].size()) {return maxcount;}if(vec[x][y] =='M') {if(k == 0) {return bfs(vec, x, y+1, k, maxcount+1);}if(k == 1) {return bfs(vec, x+1, y, k, maxcount+1);}if(k == 2) {return bfs(vec, x+1, y+1, k, maxcount+1);}if(k == 3) {return bfs(vec, x+1, y-1, k, maxcount+1);}} else {return maxcount;}
}int main() {string input;getline(cin, input);int m = input[0] - '0';int n = input[2] - '0';vector> vec(m, vector(n));for(int i = 0; i < m; i++) {getline(cin, input);int k = 0;for(int j = 0; j < n*2-1; j++) {if(j%2 == 0) {vec[i][k++] = input[j];}}}vector res;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {      if(vec[i][j] == 'M') {int maxcount = 0;for(int k = 0; k < 4; k++) {maxcount = max(maxcount, bfs(vec, i, j, k, 0));}res.push_back(maxcount);}} }sort(res.rbegin(), res.rend());cout << res[0] << endl;return 0; 
}176、 第k长的字串 、 连续字母长度
题解:
#includeusing namespace std;int cmp(pair a, pair b) {return a.second > b.second;
}int main(){string input;cin >> input;int k;cin >> k;map mp;int cnt = 0;int slow = 0;int fast = 0;while(fast < input.size()) {while(input[slow] == input[fast]) {cnt++;fast++;}mp[input[slow]] = max(mp[input[slow]], cnt);slow = fast;cnt = 0;}vector> vec(mp.begin(), mp.end());sort(vec.begin(), vec.end(), cmp);if(vec.size() < k) {cout << "-1" << endl;} else {cout << vec[k-1].second << endl;}return 0;
}177、   喊7 、 喊7  游戏 、  逢7 过 、 喊7的次数重排 、 喊七游戏
题解:  感觉类似 出租车计费 逻辑处理  
#include using namespace std;int main() {int tmp;vector vec;int count = 0;while(cin >> tmp) {vec.push_back(tmp);count += tmp;if(cin.get()=='\n') {break;}}int cnt = 1;vector res(vec.size(), 0);while(count > 0) {for(int& val : res) {if(cnt % 10 == 7 || cnt % 7 == 0) {val++;count--;}if(count == 0) {break;}cnt++;}}for(int i = 0; i < res.size(); i++) {if(i) {cout << ' ';}cout << res[i];}return 0;
}178、   猜密码  
题解:  回溯  小杨 保险柜  忘记密码
#includeusing namespace std;vector result;
vector path;void backtracking(vector& vec, int k, int startIndex) {if(path.size() >= k) {string temp = "";for(auto val : path) {temp += val + ',';}temp.erase(temp.size()-1);result.push_back(temp); }if (path.size() == vec.size()) {return;}for (int i = startIndex; i < vec.size(); i++) {path.push_back(vec[i]);backtracking(vec, k, i+1);path.pop_back();}
}int main(){string input;getline(cin, input);stringstream ss(input);vector vec;while(getline(ss, input, ',')) {vec.push_back(input);}int k;cin >> k;sort(vec.begin(), vec.end());result.clear();path.clear();backtracking(vec, k, 0);for(auto val : result) {cout << val << endl;}return 0;
}179、 寻找最大价值的矿堆
题解:   dfs  类似 力扣  0695 岛屿的最大面积   对不等于的进行遍历,取最大值
#includeusing namespace std;int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向void dfs(vector>& grid, vector>& visited, int x, int y, int& count) {for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过if (!visited[nextx][nexty] && grid[nextx][nexty] != 0) { // 没有访问过的 同时 是陆地的visited[nextx][nexty] = true;count += grid[nextx][nexty];dfs(grid, visited, nextx, nexty, count);}}
}int main() {string input;vector> grid;while(cin >> input) {vector value;for(auto ch : input) {value.push_back(ch-'0');}grid.push_back(value);}int n = grid.size(), m = grid[0].size();vector> visited = vector>(n, vector(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] != 0) {int count = grid[i][j];  // 因为dfs处理下一个节点,所以这里遇到陆地了就先计数,dfs处理接下来的相邻陆地visited[i][j] = true;dfs(grid, visited, i, j, count); // 将与其链接的陆地都标记上 trueresult = max(result, count);}}}cout << result;return 0;
}180、 最长的顺子
题解:  吴修全发明的游戏   
#include 
#include 
#include 
#include 
#include using namespace std;int main() {string myCard, outCard;getline(cin, myCard);getline(cin, outCard);map cardDict;string card;for (auto card : myCard) {if (cardDict.count(string(1, card)) > 0) {cardDict[string(1, card)] += 1;} else {cardDict[string(1, card)] = 1;}}for (auto card : outCard) {if (cardDict.count(string(1, card)) > 0) {cardDict[string(1, card)] += 1;} else {cardDict[string(1, card)] = 1;}}vector> shunzi;vector cards {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};int startindex = 0;for (int i = 0; i < cards.size(); i++) {if (cardDict.count(cards[i]) > 0) {int num = 4 - cardDict[cards[i]];if (num == 0) {if (i - startindex >= 5) {vector tmp = {startindex, i-1};shunzi.push_back(tmp);}startindex = i + 1;} else if (i == cards.size() - 1) {vector tmp {startindex, static_cast(cards.size() - 1)};shunzi.push_back(tmp);}}}int maxlength = 5;vector maxshunzi;// 存的是起始位置for (auto chain : shunzi) {if (chain[1] - chain[0] >= maxlength) {maxlength = chain[1] - chain[0];maxshunzi = chain;}}if (maxshunzi.empty()) {cout << "NO-CHAIN";} else {string result;for (int i = maxshunzi[0]; i <= maxshunzi[1]; i++) {if (i != maxshunzi[0]) {result += "-";}result += cards[i];}cout << result << endl;}return 0;
}181、  字符串统计   I
题解: 统计其中数字字符出现的次数
#include
#include
#includeusing namespace std;int main(){int n;cin >> n;cin.ignore();string input;while(n--){getline(cin, input);int count = 0;for(auto ch : input){if(isdigit(ch)) {//注意数字加引号 count++;}}cout << count << endl;}return 0;
}182、 全量和已占用字符集  、 字符串统计   、 剩余可用字符集 、 @分割可用字符集
题解:  输入  a:3,b:5,c:2@a:1,b:2  输出 a:2,b:3,c:2
#include using namespace std;int main() {string str;getline(cin, str);stringstream inputss(str);string temp;vector input;while(getline(inputss, temp, '@')) {input.push_back(temp);}if(input[1] == "") {cout << str << endl;return 0;}vector vec;map mp;for(int i = 0; i < input.size(); i++) {vector value;stringstream valuess(input[i]);string temp2;while(getline(valuess, temp2, ',')) {value.push_back(temp2);}if (i == 0) {for (int j = 0; j < value.size(); j++) {vector countinfo;stringstream countinfoss(value[j]);string temp3;while (getline(countinfoss, temp3, ':')) {countinfo.push_back(temp3);}string key = countinfo[0];int value = stoi(countinfo[1]);mp[key] = value;vec.push_back(key);}}  else {for (int j = 0; j < value.size(); j++) {stringstream countinfoss(value[j]);string temp3;vector countinfo;while (getline(countinfoss, temp3, ':')) {countinfo.push_back(temp3);}string key = countinfo[0];int value = stoi(countinfo[1]);mp[key] = mp[key] - value;}}}map notIn;for(auto val : mp) {if(val.second != 0) {notIn[val.first] = val.second;}}int len = notIn.size();int index = 0;for(auto val : notIn) {if(index) {cout << ";";}cout << val.first << ":" << val.second;index++;}return 0;
}183、  最佳植树距离   、 种树 
题解:   力扣原题  1552. 两球之间的磁力
#includeusing namespace std;// 找到某个最小磁力时,最多能放的球的个数
int check(vector &vec, int x) {int pre = vec[0], cnt = 1;for (int i = 1; i < vec.size(); ++i) {if (vec[i] - pre >= x) {pre = vec[i];cnt++;}}return cnt;
}int main() {int num;cin >> num;vector vec(num);for(int i = 0; i < vec.size(); i++) {cin >> vec[i];}int treeNum;cin >> treeNum;sort(vec.begin(), vec.end());int l = 1, r = vec.back() - vec[0];while (l <= r) {int mid = l + (r - l)/2;if (check(vec, mid) >= treeNum) {l = mid + 1;} else {r = mid - 1;}}cout <<  l - 1;return 0;
}183、  报数游戏
题解:  约瑟夫问题
#include 
#include using namespace std;int main() {int m;cin >> m;vector vec(100);for (int i = 0; i < 100; i++) {vec[i] = i + 1;}int index = 0;while (vec.size() >= m) {index = (index + m - 1) % vec.size();vec.erase(vec.begin() + index);}for (int i = 0; i < m - 1; i++) {if (i != m - 2) {cout << vec[i] << ",";} else {cout << vec[i];}}return 0;
}184、  符合条件的子串长度  、 连续子串ABV 、 寻找符合要求的最长子串
题解: 滑动窗口
#include 
#include 
#include 
using namespace std;int main() {char c;string str;cin >> c >> str;int l = 0;int res = 0;unordered_map mp;for (int r = 0; r < str.length(); r++) {mp[str[r]]++;if(str[r] == c) {if (r == str.size() - 1) {r -- ;break;}l = r + 1;mp.clear();} else {while (mp[str[r]] > 2) {mp[str[l]] -- ;l++;}}res = max(res, r - l + 1);}cout << res << endl; return 0;
}185、  选修课
题解:  字符串处理输入    存入 map 根据要求进行自定义排序
#include using namespace std;bool cmp(string a, string b){string a1 = a.substr(0,8);string a2 = a.substr(8);string b1 = b.substr(0,8);string b2 = b.substr(8);if(b2 == a2){return a1 < b1;}else{return stoi(a2) > stoi(b2);}
}vector split(string str, char ch) {vector res;stringstream ss(str);while(getline(ss, str, ch)) {res.push_back(str);}return res;
}int main() {string s1, s2;getline(cin,s1);getline(cin,s2);vector v1 = split(s1, ';');vector v2 = split(s2, ';');map> mp1;for(auto v : v1){vector tmp = split(v, ',');mp1[tmp[0]].push_back(tmp[1]);}for(auto v : v2){vector tmp = split(v,',');mp1[tmp[0]].push_back(tmp[1]);}map> mp2;for(auto m1:mp1){if(m1.second.size() == 2){string k = m1.first.substr(0,5);string score1 = m1.second[0];string score2 = m1.second[1];int score = stoi(score1)+stoi(score2);mp2[k].push_back(m1.first + to_string(score));}}if(mp2.size() == 0) {cout<<"NONE"<using namespace std;bool cmp(vector a, vector b){int n = a.size();int sa = 0, sb = 0;for(int i = 1; i < n; i++){sa += a[i];sb += b[i];}if(sa != sb){return sa > sb;}else {for(int i = 10; i >= 1; i--){int ca = 0, cb = 0;for(int j = 1; j < n; j++){if(a[j] == i){ca++;}if(b[j] == i){cb++;}}if(ca != cb){return ca > cb;}}}return 1;
}vector split(string str, char ch) {vector res;stringstream ss(str);while(getline(ss, str, ch)) {res.push_back(stoi(str));}return res;
}int main() {string str;getline(cin, str);vector v1 = split(str, ',');int m = v1[0];int n = v1[1];int flag = 0;if(n < 3) {flag = 1;}vector> vec;for(int i = 0; i < m; i++) {getline(cin, str);vector v2 = split(str, ',');for(int j = 0; j < n; j++) {if(v2[j] < 0 || v2[j] > 10) {flag = 1;}}vec.push_back(v2);}if(flag) {cout << "-1" << endl;} else {vector> res;for(int j = 0; j < n; j++){vector tmp;tmp.push_back(j + 1);for(int i = 0; i < m; i++){tmp.push_back(vec[i][j]);}res.push_back(tmp);}sort(res.begin(), res.end(), cmp);for(int i = 0; i < 3; i++){cout << res[i][0];if(i!=2) cout<<",";}cout << endl;}return 0;
}187、 字符统计及重排
题解: 输入 xyxyXX  输出 x:2;y:2;X:2;
#include using namespace std;int main()
{string str;getline(cin, str);vector  vec(256,0);int maxx = 0;for (char ch : str) {vec[(int)ch]++;maxx = max(maxx, vec[(int)ch]);}for (int i = maxx; i > 0; i--) {for (int j = 97; j < 123; j++) {if (vec[j] == i) {cout << (char)j << ":" << to_string(i) << ";";}}for (int j = 65; j < 91; j ++) {if (vec[j] == i) {cout << (char)j << ":" << to_string(i) << ";";}}}return 0;
}188、 最长连续子序列   
题解:
#include using namespace std;vector split(string str, char ch) {vector res;stringstream ss(str);while(getline(ss, str, ch)) {res.push_back(stoi(str));}return res;
}int main() {string str;getline(cin, str);vector nums = split(str, ',');int target;cin >> target;int ans = -1;for (int i = 0; i < nums.size(); i++) {int cursum = 0;for (int j = i; j < nums.size(); j++) {cursum += nums[j];if (cursum == target) {ans = max(ans, j - i + 1);}}}cout << ans << endl;return 0;
}189、  字符串重新排序    、 字符串重新排列 
题解: 输入 This is an apple   输出 an is This aelpp
#include using namespace std;unordered_map mp;int cmp(string t1,string t2) {if(mp[t1] == mp[t2]){if(t1.size() == t2.size()){return t1 < t2;}return t1.size() < t2.size();}return mp[t1] > mp[t2];
}int main(){string str;getline(cin,str);stringstream ss(str);vector value;while(ss >> str) {value.push_back(str);}for(int i = 0; i < value.size(); i++){sort(value[i].begin(), value[i].end());if(mp.count(value[i]) > 0) {mp[value[i]]++;} else {mp[value[i]] = 1;}}sort(value.begin(), value.end(), cmp);for(int i = 0; i < value.size(); i++){if(i) {cout << " ";}cout << value[i];}return 0;
}190、 最多等和不相交连续子序列
题解:
#include using namespace std;int checkFun(vector> vec) {int maxlen = 0;for(int i = 0; i < vec.size(); i++) {vector> res;res.push_back(vec[i]);int right = vec[i][1];for(int j = 0; j < vec.size(); j++) {if(i == j) {continue;}int left = vec[j][0];if(left > right) {res.push_back(vec[j]);right = vec[j][1];}}int tmp = res.size();maxlen = max(maxlen, tmp);}return maxlen;
}vector split(string str, char ch) {vector res;stringstream ss(str);while(getline(ss, str, ch)) {res.push_back(stoi(str));}return res;
}int main() {string str;getline(cin, str);int n = stoi(str);vector vec;getline(cin, str);vec = split(str, ' ');map>> mp;for(int i = 0; i < n; i++) {int sum = 0;for(int j = i; j < n; j++) {sum += vec[j];mp[sum].push_back({i,j});}}int res = 0;for(auto m : mp) {res = max(res, checkFun(m.second));}cout << res << endl;return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部