1
100
环中最长子串/最长子字符串长度(一)v
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s; // 读取输入字符串
int count = 0; // 初始化'o'的计数器
for (auto x : s) {
if (x == 'o') count++;
}
int tar = (count % 2 == 0) ? s.size() : s.size() - 1;
cout << tar << endl; // 输出结果
return 0;
}
#include <iostream>
#include <string>
class CharacterCounter {
private:
std::string str;
int n;
int i;
public:
CharacterCounter() : n(0), i(0) {}
void readInput() {
std::cin >> str;
}
void countCharacters() {
while (str[i] != '\0') {
if (str[i] == 'o') {
n++;
}
i++;
}
}
void printResult() const {
std::cout << (n % 2 ? i - 1 : i) << std::endl;
}
};
int main() {
CharacterCounter characterCounter;
characterCounter.readInput();
characterCounter.countCharacters();
characterCounter.printResult();
return 0;
}
螺旋数字矩阵v
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // For std::for_each
using namespace std;
// 递归填充螺旋矩阵
void fillSpiral(vector<vector<string>>& res, int x, int y, int n, int m, int& k, int dx[], int dy[], int& dir) {
// 结束条件:当数字超过n时停止
if (k > n) return;
// 填充当前位置
res[x][y] = to_string(k++);
// 计算下一个位置
int a = x + dx[dir];
int b = y + dy[dir];
// 如果下一个位置超出界限或已填充,改变方向
if (a < 0 || a >= m || b < 0 || b >= (n + m - 1) / m || res[a][b] != "*") {
// 改变方向(顺时针旋转)
dir = (dir + 1) % 4;
a = x + dx[dir];
b = y + dy[dir];
}
// 递归填充下一个位置
fillSpiral(res, a, b, n, m, k, dx, dy, dir);
}
int main() {
int n, m;
cin >> n >> m;
int L = (n + m - 1) / m;
vector<vector<string>> res(m, vector<string>(L, "*"));
int dx[] = {0, 1, 0, -1}; // 右, 下, 左, 上
int dy[] = {1, 0, -1, 0};
int k = 1; // 起始数字
int dir = 0; // 初始方向为右
fillSpiral(res, 0, 0, n, m, k, dx, dy, dir);
// 使用 std::for_each 输出结果矩阵
for_each(res.begin(), res.end(), [](const vector<string>& row) {
for_each(row.begin(), row.end(), [](const string& cell) {
cout << cell << ' ';
});
cout << endl;
});
return 0;
}
#include <iostream>
#include <vector>
#include <string>
class SpiralMatrix {
private:
int nums;
int n;
int m;
std::vector<std::vector<std::string>> res;
public:
SpiralMatrix() : nums(0), n(0), m(0) {}
void readInput() {
std::cin >> nums >> n;
m = (nums - 1) / n + 1;
res.resize(n, std::vector<std::string>(m, "*"));
generateSpiralMatrix();
}
void generateSpiralMatrix() {
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
for (int x = 0, y = 0, d = 0, k = 1; k <= nums; k++) {
res[x][y] = std::to_string(k);
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || res[a][b] != "*") {
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
}
void printResult() const {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
std::cout << res[i][j] << ' ';
}
std::cout << std::endl;
}
}
};
int main() {
SpiralMatrix spiralMatrix;
spiralMatrix.readInput();
spiralMatrix.printResult();
return 0;
}
最富裕的小家庭v
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> num, val;
int sum;
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
{
int a;
cin >> a;
num.push_back(a);
val.push_back(a);
}
for (int i = 0; i < n - 1; i++)
{
int a, b;
cin >> a >> b;
a--;
b--;
val[a] += num[b];
}
sum = val[0];
for (int i = 0; i < n; i++)
{
sum = max(val[i],sum);
}
cout << sum << endl;
return 0;
}
找座位/
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s; // 读取输入字符串
int count = 0; // 初始化计数器,用于记录修改次数
for (int i = 0; i < s.size(); i++) {
if (s[i] == '1') {
// 如果当前字符是 '1',检查并跳过下一个字符
i++;
} else {
// 分开检查左邻居
bool leftEmpty;
if (i == 0) {
leftEmpty = true; // 在字符串的起始位置,左边为空
} else {
leftEmpty = (s[i - 1] == '0'); // 检查左边是否是 '0'
}
// 分开检查右邻居
bool rightEmpty;
if (i == s.size() - 1) {
rightEmpty = true; // 在字符串的末尾位置,右边为空
} else {
rightEmpty = (s[i + 1] == '0'); // 检查右边是否是 '0'
}
// 如果左右邻居都为空,将当前字符设为 '1'
if (leftEmpty && rightEmpty) {
s[i] = '1'; // 将当前字符设为 '1'
count++; // 修改次数加一
i++; // 跳过下一个字符的处理
}
}
}
cout << count << endl; // 输出修改次数
return 0;
}
密码输入检测v
#include <iostream>
#include <vector>
using namespace std;
// 更新计数器的辅助函数
void updateCounts(int& small, int& big, int& number, int& special, char c, int delta) {
switch (c) {
case 'a' ... 'z': // C++20 才支持的范围
small += delta;
break;
case 'A' ... 'Z':
big += delta;
break;
case '0' ... '9':
number += delta;
break;
default:
special += delta;
break;
}
}
// 处理字符并更新栈及计数器的辅助函数
void processCharacter(vector<char>& stack, char c, int& small, int& big, int& number, int& special) {
if (c == '<') { // 处理退格符
if (!stack.empty()) {
char removed = stack.back();
stack.pop_back();
updateCounts(small, big, number, special, removed, -1);
}
} else { // 添加字符
stack.push_back(c);
updateCounts(small, big, number, special, c, 1);
}
}
int main() {
string s;
cin >> s; // 读取输入字符串
vector<char> stack; // 初始化栈,用于处理退格操作
int small = 0; // 统计小写字母的数量
int big = 0; // 统计大写字母的数量
int number = 0; // 统计数字的数量
int special = 0; // 统计特殊字符的数量
// 使用 while 循环遍历字符串中的每个字符
int i = 0;
int len = s.length();
while (i < len) {
char c = s[i];
processCharacter(stack, c, small, big, number, special);
++i;
}
// 判断密码是否安全
bool safe = stack.size() >= 8 && small >= 1 && big >= 1 && number >= 1 && special >= 1;
// 输出处理后的字符串
for (char c : stack) cout << c;
// 输出密码是否安全的结果
cout << (safe ? ",true" : ",false");
return 0; // 返回 0 表示程序成功执行
}
分配土地/
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 500;
int main() {
int m, n;
cin >> m >> n; // 输入网格的行数和列数
//
vector<vector<int>> nums(MAX_SIZE, vector<int>(4, -1));
// 处理网格中的每个元素
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int num;
cin >> num; // 输入表示矩形的数字
if (num > 0) { // 如果数字大于0(表示存在矩形)
// 更新对应矩形的边界
if (nums[num][0] == -1) { // 如果是第一次更新这个矩形的边界
nums[num][0] = nums[num][1] = i; // minRow = maxRow = 当前行索引
nums[num][2] = nums[num][3] = j; // minCol = maxCol = 当前列索引
}
else {
nums[num][0] = min(nums[num][0], i); // 更新minRow
nums[num][1] = max(nums[num][1], i); // 更新maxRow
nums[num][2] = min(nums[num][2], j); // 更新minCol
nums[num][3] = max(nums[num][3], j); // 更新maxCol
}
}
}
}
int maxArea = 0;
// 遍历所有可能的矩形
for (int i = 0; i < MAX_SIZE; i++) {
if (nums[i][0] != -1) { // 如果存在这个数字对应的矩形
int minRow = nums[i][0];
int maxRow = nums[i][1];
int minCol = nums[i][2];
int maxCol = nums[i][3];
int area = (maxRow - minRow + 1) * (maxCol - minCol + 1); // 计算矩形的面积
maxArea = max(maxArea, area); // 更新最大面积
}
}
cout << maxArea << endl; // 输出找到的最大面积
return 0; // 程序结束
}
#include <iostream>
#include <vector>
#include <climits>
const int MAX_SIZE = 500;
class Rect {
public:
int minRow;
int maxRow;
int minCol;
int maxCol;
Rect() : minRow(INT_MAX), maxRow(INT_MIN), minCol(INT_MAX), maxCol(INT_MIN) {}
void updateBounds(int row, int col) {
minRow = std::min(minRow, row);
maxRow = std::max(maxRow, row);
minCol = std::min(minCol, col);
maxCol = std::max(maxCol, col);
}
int calculateArea() const {
return (maxRow - minRow + 1) * (maxCol - minCol + 1);
}
};
class RectanglesAnalyzer {
private:
std::vector<Rect*> rects;
public:
RectanglesAnalyzer() : rects(MAX_SIZE, nullptr) {}
void processInput() {
int m, n;
std::cin >> m >> n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int num;
std::cin >> num;
if (num > 0) {
if (rects[num] == nullptr) {
rects[num] = new Rect();
}
rects[num]->updateBounds(i, j);
}
}
}
}
int calculateMaxArea() const {
int maxArea = 0;
for (int i = 0; i < MAX_SIZE; i++) {
Rect* rect = rects[i];
if (rect != nullptr) {
int area = rect->calculateArea();
maxArea = std::max(maxArea, area);
delete rect; // Don't forget to free memory
}
}
return maxArea;
}
};
int main() {
RectanglesAnalyzer analyzer;
analyzer.processInput();
int maxArea = analyzer.calculateMaxArea();
std::cout << maxArea << std::endl;
return 0;
}
智能成绩表x
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
struct comparator {
int idx; // 排序依据的索引
// 构造函数,初始化排序索引
comparator(int a) : idx(a) {}
// 比较函数,用于排序
bool operator()(const pair<string, vector<int>>& a, const pair<string, vector<int>>& b) const
{
if (a.second[idx] != b.second[idx]) return a.second[idx] > b.second[idx];
else return a.first < b.first; // 如果成绩相同,按姓名升序排序
}
};
int main() {
int n, m;
cin >> n >> m; // 读取学生人数和科目数量
// 存储科目名称和对应的出现顺序索引
unordered_map<string, int> subject_idx;
for (int i = 0; i < m; ++i) {
string subject;
cin >> subject;
subject_idx[subject] = i; // 将科目名称与索引映射存入 map 中
}
// pair存学生信息,一个名字对应很多成绩,如果需要按名字查找就用map了
vector<pair<string, vector<int>>> chengji;
// 读取每个学生的信息
for (int i = 0; i < n; ++i) {
string name;
cin >> name;
vector<int> scores(m); // 存储当前学生的各科成绩
int score_sum = 0; // 记录当前学生的总分
// 读取每个科目的成绩
for (int j = 0; j < m; ++j) {
cin >> scores[j];
score_sum += scores[j]; // 计算总分
}
scores.push_back(score_sum); // 将总分添加到 scores 后面
// 将学生姓名和成绩 vector 存入 chengji 中
chengji.emplace_back(name, scores);
}
string object;
cin >> object; // 输入用作排名的目标科目名称
// 获取用作排名的科目对应的索引,如果不存在,则默认使用总分索引 m
int idx = subject_idx.count(object) > 0 ? subject_idx[object] : m;
// 创建比较函数对象
comparator comparator(idx);
// 使用比较函数对象进行排序:首先按指定科目成绩降序排序,如果成绩相同则按姓名升序排序
sort(chengji.begin(), chengji.end(), comparator);
// 输出排序后的结果
for (const auto& student : chengji) {
cout << student.first << " ";
}
cout << endl;
return 0;
}
转盘寿司v
只要有比当前寿司小的,总是能被送出去;送出去的是离他最近的下一个寿司。把价格加起来输出就行
存价格,初始化结果数组res,存索引栈stk。遍历数组两次处理
开两倍数组解决循环的问题,思路是用单调栈来解决。左边离目标最近的最小值,是从0开始递增,越往后的越靠近目标的左边,所以只要是小的,栈里的其他元素就永无出头之日。右边离目标最近的最小的是从最后开始递减,越往后的越靠近目标的右边。开双倍数组的时候,记得 i = 2 * n - 1;且目标为i% n;保证每次对应的都是目标的索引。这样就可以循环一边更新。也就是目标的左边一个,是目标右边离目标最远的元素。
#include <iostream> // 引入输入输出流
#include <vector> // 引入动态数组容器
using namespace std; // 使用标准命名空间
// 计算每个价格对应的结果数组
vector<int> calculatePrices(const vector<int>& prices) {
int n = prices.size(); // 获取价格数组的大小
vector<int> res(n); // 创建结果数组,初始化为0
// 遍历每一个价格
for (int i = 0; i < n; ++i) {
int cur = prices[i]; // 当前价格
int sum = cur; // 初始化为当前价格
// 从当前价格的下一个位置开始向前查找
for (int j = (i + 1) % n; j != i; j = (j + 1) % n) {
// 如果找到比当前价格小的价格
if (prices[j] < cur) {
sum += prices[j]; // 将找到的价格加到结果中
break; // 退出查找
}
}
// 将计算结果存入结果数组
res[i] = sum;
}
return res; // 返回结果数组
}
int main() {
vector<int> prices; // 存储输入的价格
int price; // 当前读取的价格
// 从标准输入读取价格直到输入结束
while (cin >> price) {
prices.push_back(price); // 将读取的价格添加到价格数组中
}
// 调用 calculatePrices 函数计算结果
vector<int> res = calculatePrices(prices);
// 输出结果数组的第一个元素
cout << res[0];
// 从第二个元素开始输出其余结果,前面加空格
for (int i = 1; i < res.size(); ++i) {
cout << " " << res[i];
}
return 0; // 程序正常结束
}
开源项目热度榜单x
字典序排序 热度降序
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//项目对象
struct project {
string name; // 项目名称
int hot; // 项目热度
string name_lower; // 项目名称的小写形式
};
const int N = 110;
int n, w[5];
project a[N];//对象数组
// 自定义比较函数对象
struct CompareProjects {
bool operator()(const project& a, const project& b) const {
if (a.hot != b.hot) {
return a.hot > b.hot; // 按热度降序
}
return a.name_lower < b.name_lower; // 热度相同则按名称升序
}
};
int main() {
cin >> n; // 读取总项目数
for (int i = 0; i < 5; i++)
cin >> w[i]; // 读取权重数组
// 处理每个项目
for (int i = 0; i < n; i++) {
string s;
vector<int> wd(5);
cin >> s >> wd[0] >> wd[1] >> wd[2] >> wd[3] >> wd[4];
int hot = 0;
// 计算项目热度,热度为每个权重乘以对应值的总和
for (int j = 0; j < 5; j++) {
hot += wd[j] * w[j];
}
string t = s;
transform(t.begin(), t.end(), t.begin(), ::tolower); // 将项目名称转换为小写形式
a[i] = { s, hot, t };
}
// 使用自定义的比较函数对象进行排序
sort(a, a + n, CompareProjects());
// 输出排序后的项目名称
for (int i = 0; i < n; i++)
cout << a[i].name << endl;
return 0;
}
提取字符串中的最长合法简单数学表达式v
#include <iostream>
#include <string>
#include <regex>
using namespace std;
typedef long long LL;
int main() {
string line;
getline(cin, line); // 读取输入行
long long res = 0; // 存储结果
int maxLen = 0; // 存储最长匹配的长度
int len = line.length(); // 输入字符串长度
regex pattern("(\\d+)([*+-])(\\d+)"); // 正则表达式模式
smatch match; // 用于存储匹配结果
// 双指针初始化
int start = 0;
while (start < len) {
int end = start + maxLen; // 从当前最长匹配长度开始检查
while (end < len) {
string sub = line.substr(start, end - start + 1); // 提取子字符串
// 如果子字符串匹配模式且长度大于maxLen
if (regex_search(sub, match, pattern)) {
int currentLen = end - start + 1;
if (currentLen > maxLen) {
maxLen = currentLen; // 更新最大长度
long long first = stoll(match[1]); // 转换第一个数字
string op = match[2]; // 操作符
long long second = stoll(match[3]); // 转换第二个数字
// 根据操作符计算结果
if (op == "+") {
res = first + second;
}
else if (op == "-") {
res = first - second;
}
else if (op == "*") {
res = first * second;
}
}
}
end++;
}
start++;
}
cout << res << endl; // 输出结果
return 0;
}
机器人搬砖/
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
vector<int> s; // 保存输入的数组
// 检查是否能用 maxCount 作为最大值分割为不超过 8 组
int check(const vector<int>& w, int maxCount) {
int totalGroups = 0;
for (int value : w) {
totalGroups += (value + maxCount - 1) / maxCount;
}
return totalGroups;
}
int main() {
int x;
while (cin >> x) s.push_back(x);
int n = s.size();
// 如果项目数超过 8,直接输出 -1
int result = (n > 8) ? -1 :
// 二分查找的起始范围
[s]() {
int l = 1, r = *max_element(s.begin(), s.end());
while (l < r) {
int mid = l + (r - l) / 2;
if (check(s, mid) <= 8) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}(); // 立即调用 lambda 表达式
// 输出结果
cout << result << endl;
return 0;
}
内存冷热标记/
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, T, x;
unordered_map<int, int> cnt;
vector<pair<int, int>> items; // 使用vector来存储元素和它们的频率
cin >> n;
// 读取输入并统计频率
for (int i = 0; i < n; ++i) {
cin >> x;
cnt[x]++;
}
cin >> T;
// 将符合条件的元素和频率添加到vector
for (const auto& [num, frequency] : cnt) {
if (frequency >= T) {
items.push_back({frequency, num});
}
}
// 对vector中的元素进行排序
sort(items.begin(), items.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first != b.first) return a.first > b.first; // 按频率降序排序
return a.second < b.second; // 按编号升序排序
});
// 输出符合条件的元素数量
cout << items.size() << endl;
// 输出排序后的结果
for (const auto& item : items) {
cout << item.second << endl;
}
return 0;
}
虚拟理财游戏v
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct product {
int re;
int risk;
int maxinvest;
};
int main() {
int n, investsum, risksum;
cin >> n >> investsum >> risksum;
vector<product> pro(n);
for (int i = 0; i < n; ++i) {
cin >> pro[i].re;
}
for (int i = 0; i < n; ++i) {
cin >> pro[i].risk;
}
for (int i = 0; i < n; ++i) {
cin >> pro[i].maxinvest;
}
int maxsum = 0;
vector<int> res(n);
for (int i = 0; i < n; ++i) {
if (pro[i].risk <= risksum) {
int invest = min(pro[i].maxinvest, investsum);
int sum = invest * pro[i].re;
if (sum > maxsum) {
vector<int> temp(n, 0);
temp[i] = invest;
res = temp;
maxsum = sum;
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int re1 = pro[i].re;
int risk1 = pro[i].risk;
int maxinvest1 = pro[i].maxinvest;
int re2 = pro[j].re;
int risk2 = pro[j].risk;
int maxinvest2 = pro[j].maxinvest;
if (risk1 + risk2 <= risksum) {
if (re1 > re2) {
int remaininvest;
if (investsum <= maxinvest1) {
remaininvest = 0;
maxinvest1 = investsum;
}
else {
remaininvest = min(maxinvest2, investsum - maxinvest1);
}
int sum = remaininvest * re2 + maxinvest1 * re1;
if (sum > maxsum) {
vector<int> temp(n, 0);
temp[i] = maxinvest1;
temp[j] = remaininvest;
res = temp;
maxsum = sum;
}
}
else if (re1 < re2) {
int remaininvest;
if (investsum <= maxinvest2) {
maxinvest2 = investsum;
remaininvest = 0;
}
else {
remaininvest = min(maxinvest1, investsum - maxinvest2);
}
int sum = remaininvest * re1 + maxinvest2 * re2;
if (sum > maxsum) {
vector<int> temp(n, 0);
temp[j] = maxinvest2;
temp[i] = remaininvest;
res = temp;
maxsum = sum;
}
}
else {
if (risk1 < risk2) {
int remaininvest;
if (investsum <= maxinvest1) {
maxinvest1 = investsum;
remaininvest = 0;
}
else {
remaininvest = min(maxinvest2, investsum - maxinvest1);
}
int sum = remaininvest * re2 + maxinvest1 * re1;
if (sum > maxsum) {
vector<int> temp(n, 0);
temp[i] = maxinvest1;
temp[j] = remaininvest;
res = temp;
maxsum = sum;
}
}
else {
int remaininvest;
if (investsum <= maxinvest2) {
maxinvest2 = investsum;
remaininvest = 0;
}
else {
remaininvest = min(maxinvest1, investsum - maxinvest2);
}
int sum = remaininvest * re1 + maxinvest2 * re2;
if (sum > maxsum) {
vector<int> temp(n, 0);
temp[j] = maxinvest2;
temp[i] = remaininvest;
res = temp;
maxsum = sum;
}
}
}
}
}
}
for (int i = 0; i < n; ++i) {
cout << res[i] << " ";
}
}
游戏分组v
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int nums[10];
int total = 0;
int res = 1e9; // 差距最小值
int main()
{
vector<int> original(10);
vector<int> subset(5);
// 读取输入并计算总和
for (int i = 0; i < 10; i++) {
cin >> nums[i];
total += nums[i];
original[i] = i; // 保存下标
}
// 生成所有的5个数的组合
do {
// 选择5个元素
for (int i = 0; i < 5; i++) {
subset[i] = nums[original[i]];
}
// 计算选择的5个数的和
int sum1 = 0;
for (int i = 0; i < 5; i++) {
sum1 += subset[i];
}
// 计算差值并更新最小差值
res = min(res, abs(total - 2 * sum1));
} while (next_permutation(original.begin(), original.end()));
cout << res << endl;
return 0;
}
围棋的气/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
const int BOARD_SIZE = 19; // 棋盘的大小
vector<vector<int>> board(BOARD_SIZE, vector<int>(BOARD_SIZE, 0)); // 初始化一个19x19的棋盘,所有位置初始为0
vector<int> black_positions, white_positions; // 保存黑棋和白棋的位置
vector<int> dx = { -1, 1, 0, 0 }; // 方向数组,用于上下左右移动
vector<int> dy = { 0, 0, 1, -1 }; // 方向数组,用于上下左右移动
// 读取棋子的位置信息
void read_positions(vector<int>& positions) {
string input;
getline(cin, input); // 获取整行输入
stringstream ss(input); // 使用字符串流处理输入
int num;
while (ss >> num) { // 逐个读取整数
positions.push_back(num); // 将读取的整数加入到positions向量中
}
}
// 在棋盘上放置棋子
void place_stones(vector<int>& positions, int stone) {
for (int i = 0; i < positions.size(); i += 2) { // 每两个数字表示一个棋子的坐标
int x = positions[i], y = positions[i + 1]; // 获取棋子的坐标
board[x][y] = stone; // 在棋盘上对应位置放置棋子
}
}
// 计算棋子的气(liberties)
int count_liberties(int stone) {
int liberties = 0; // 初始化气的数量
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
if (board[i][j] == 0) { // 如果当前位置为空
bool has_liberty = false; // 初始化是否有气的标志
for (int dir = 0; dir < 4; ++dir) { // 遍历四个方向
int x = i + dx[dir], y = j + dy[dir]; // 计算新位置
if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == stone) {
has_liberty = true; // 如果新位置有同色棋子,则当前位置有气
break;
}
}
if (has_liberty) {
++liberties; // 计数
}
}
}
}
return liberties; // 返回气的数量
}
int main() {
read_positions(black_positions); // 读取黑棋位置
read_positions(white_positions); // 读取白棋位置
place_stones(black_positions, 1); // 在棋盘上放置黑棋
place_stones(white_positions, 2); // 在棋盘上放置白棋
int black_liberties = count_liberties(1); // 计算黑棋的气
int white_liberties = count_liberties(2); // 计算白棋的气
cout << black_liberties << " " << white_liberties << endl; // 输出黑棋和白棋的气
return 0;
}
万能字符单词拼写、掌握的单词个数m
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> words(n);
for (int i = 0; i < n; ++i) {
cin >> words[i];
}
string chars;
cin >> chars;
map<char, int> mp;
for (int i = 0; i < chars.size(); ++i) {
char ch = chars[i];
mp[ch] += 1;
}
int res = 0;
for(int i = 0; i < n; ++i){
string word = words[i];
map<char, int> temp = mp;
int j = 0;
for(; j < word.length(); ++j){
char ch = word[j];
temp[ch]--;
if(temp[ch] < 0 && temp['?'] <= 0){
break;
}
else if (temp[ch] < 0 && temp['?'] > 0){
temp['?']--;
}
}
if(j == word.length()){
res++;
}
}
cout << res;
}
小明找位置x
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
const int N = 10010;
int x, num;
string str;
vector<int> nums;
int main() {
// 读取输入字符串
getline(cin, str);
stringstream ss(str);
// 将输入字符串中的数字提取到 nums 向量中
while (ss >> num) {
nums.push_back(num);
if (ss.peek() == ',') ss.ignore();
}
// 读取目标值 x
cin >> x;
// 线性扫描查找第一个大于等于 x 的元素的位置
for (int i = 0; i < nums.size(); i++) {
if (nums[i] >= x) {
cout << i + 1 << endl; // 输出位置(1-based index)
return 0; // 结束程序
}
}
// 如果没有找到满足条件的元素,输出 0
cout << 0 << endl;
return 0;
}
分割均衡字符串/
#include<bits/stdc++.h>
using namespace std;
string s;
int res, sum;
int main()
{
cin>>s;
for(char &ch:s){
if(ch=='X')sum++;
else sum--;
if(sum==0)res++;
}
cout<<res<<endl;
return 0;
}
小华地图寻宝/
#include <iostream>
#include <vector>
using namespace std;
// 定义四个方向的偏移量数组:右、下、上、左
vector<vector<int>> d = { {0, 1}, {1, 0}, {-1, 0}, {0, -1} };
// 计算一个数的各位数字之和
int cal_digit_sum(int n) {
int sum = 0;
while (n != 0) {
sum += n % 10; // 取出最低位的数字并累加到sum中
n /= 10; // 将n去掉最低位
}
return sum;
}
// 全局变量,用于记录符合条件的格子数量
int ans = 0;
// 深度优先搜索函数,用来搜索从(i, j)开始,值不超过k的所有格子
void dfs(int i, int j, int m, int n, int k, vector<vector<int>>& checklist, vector<vector<int>>& grid) {
checklist[i][j] = 1; // 标记(i, j)已访问
ans++; // 符合条件的格子数量加1
for (auto& dir : d) { // 遍历四个方向
int ni = i + dir[0]; // 新的行坐标
int nj = j + dir[1]; // 新的列坐标
// 检查新的坐标是否在范围内且未被访问过,并且格子的值不超过k
if (ni >= 0 && ni < m && nj >= 0 && nj < n && checklist[ni][nj] == 0 && grid[ni][nj] <= k) {
dfs(ni, nj, m, n, k, checklist, grid); // 递归调用dfs,继续搜索
}
}
}
int main() {
int m, n, k;
cin >> m >> n >> k; // 输入迷宫的行数m,列数n,以及格子值不超过k的条件
vector<vector<int>> grid(m, vector<int>(n, 0)); // 创建迷宫格子的二维数组
vector<vector<int>> checklist(m, vector<int>(n, 0)); // 创建访问标记的二维数组
// 初始化迷宫格子的值,每个格子的值为行坐标和列坐标的各位数字之和
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
grid[i][j] = cal_digit_sum(i) + cal_digit_sum(j);
}
}
if (m == 0 && n == 0) cout << 0;
else
{
// 从(0, 0)位置开始深度优先搜索,查找符合条件的所有格子
dfs(0, 0, m, n, k, checklist, grid);
// 输出符合条件的格子数量
cout << ans << endl;
}
return 0; // 程序结束
}
数的分解m
#include <climits>
#include <cmath>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if(n >= INT_MAX){
cout << "N";
return 0;
}
if (n % 2 != 0) {
cout << n << "=" << n / 2 << "+" << n / 2 + 1;
}
else {
int x = n / 2;
while (x % 2 == 0) {
x = x / 2;
}
if (x == 1) {
cout << "N";
return 0;
}
int minoddlen;
for (int i = 3; i <= x; i += 2) {
if (n % i == 0) {
minoddlen = i;
break;
}
}
int minoddstart = n / minoddlen - minoddlen / 2;
int minevenlen = n / x * 2;
int minevenstart = x / 2 - minevenlen / 2 + 1;
int start, len;
if (minoddstart <= 0 && minevenstart <= 0) {
cout << 'N';
return 0;
}
else if (minoddstart <= 0) {
start = minevenstart;
len = minevenlen;
}
else if (minevenstart <= 0) {
start = minoddstart;
len = minoddlen;
}
else {
if (minoddlen < minevenlen) {
start = minoddstart;
len = minoddlen;
}
else {
start = minevenstart;
len = minevenlen;
}
}
cout << n << "=" << start;
for (int i = 1; i < len; ++i) {
cout << "+" << start + i;
}
}
}
执行任务赚积分v
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
int main() {
int n, T;
cin >> n >> T;
vector<PII> tasks(n);
for (int i = 0; i < n; ++i) {
int a, b;
cin >> a >> b;
tasks[i] = {a, b};
}
// 按结束时间升序排序任务
sort(tasks.begin(), tasks.end());
// 使用动态数组来存储每个时间点的最大积分
vector<int> dp(T + 1, 0);
for (const auto& task : tasks) {
int deadline = task.first;
int points = task.second;
// 从后往前更新动态规划数组
for (int j = T; j >= 1; --j) {
if (j <= deadline) {
dp[j] = max(dp[j], dp[j - 1] + points);
}
}
}
// 找到动态规划数组中的最大值
int totalPoints = *max_element(dp.begin(), dp.end());
cout << totalPoints << endl;
return 0;
}
计算三叉搜索树的高度v
#include <iostream>
#include <vector>
#include <algorithm> // for max function
using namespace std;
// 构建树节点结构体
struct Node {
int val;
Node* left;
Node* mid;
Node* right;
Node(int v) : val(v), left(nullptr), mid(nullptr), right(nullptr) {}
};
// 定义全局变量ans,用于记录树的最大高度
int ans = 1;
void dfs(Node& cur_node, int val, int hight) {
if (cur_node.val - val < -500) {
if (cur_node.left == nullptr) {
cur_node.left = new Node(val);
ans = max(ans, hight + 1);
return;
}
dfs(*cur_node.left, val, hight + 1);
}
else if (cur_node.val - val > 500) {
if (cur_node.right == nullptr) {
cur_node.right = new Node(val);
ans = max(ans, hight + 1);
return;
}
dfs(*cur_node.right, val, hight + 1);
}
else {
if (cur_node.mid == nullptr) {
cur_node.mid = new Node(val);
ans = max(ans, hight + 1);
return;
}
dfs(*cur_node.mid, val, hight + 1);
}
}
int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
Node* root = new Node(nums[0]);
for (int i = 1; i < n; ++i) {
dfs(*root, nums[i], 1);
}
cout << ans << endl;
return 0;
}
API集群负载统计m
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<vector<string>> url(n);
for (int i = 0; i < n; ++i) {
string str;
cin >> str;
str.erase(0, 1);
int pos = str.find('/');
while (pos != -1) {
string key = str.substr(0, pos);
url[i].push_back(key);
str = str.substr(pos + 1, str.size());
pos = str.find('/');
}
url[i].push_back(str);
}
int l;
cin >> l;
string key;
cin >> key;
int res = 0;
for(int i = 0; i < n; ++i){
if(url[i].size() >= l){
if(url[i][l - 1] == key){
res++;
}
}
}
cout << res;
}
剩余银饰的重量m
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> weight(n);
for (int i = 0; i < n; ++i) {
cin >> weight[i];
}
sort(weight.begin(), weight.end(), greater<int>());
while (weight.size() >= 3) {
int x = weight[0];
int y = weight[1];
int z = weight[2];
int temp;
weight.erase(weight.begin(), weight.begin() + 3);
if (x == y && y != z) {
temp = y - z;
}
else if (x != y && y == z) {
temp = x - y;
}
else if (x != y && y != z) {
temp = abs((y - z) - (x - y));
}
else {
continue;
}
if(temp == 0){
continue;
}
int flag = 1;
for (int i = 0; i < weight.size(); ++i) {
if (temp > weight[i]) {
weight.insert(weight.begin() + i, temp);
flag = 0;
break;
}
}
if (flag) {
weight.push_back(temp);
}
}
if (weight.size() == 0) {
cout << 0;
}
else {
cout << weight[0];
}
}
最多购买宝石数目m
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> gems(n);
for (int i = 0; i < n; ++i) {
cin >> gems[i];
}
int val;
cin >> val;
int maxsum = accumulate(gems.begin(), gems.end(), 0);
if (maxsum <= val) {
cout << n;
return 0;
}
int l = 0;
int r = 0;
int sum = 0;
int count = 0;
while (r < n) {
sum += gems[r];
if (r == n - 1 && sum <= val) {
count = max(count, r - l + 1);
break;
}
if (sum > val) {
count = max(count, r - l);
while (l <= r && sum > val) {
sum -= gems[l];
l++;
}
}
r++;
}
cout << count;
}
连续字母长度v
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
int k;
cin >> s >> k; // 输入字符串 s 和整数 k
vector<int> max_lengths(26, 0); // 存储每个字母的最长连续子串长度,初始化为0,共有26个字母
int len = s.size(); // 获取字符串 s 的长度
int cur_len = 1; // 当前连续子串长度的计数器,默认为1(至少包含当前字符)
// 遍历字符串 s,找到每个字符的最长连续子串长度
for (int i = 1; i < len; ++i) {
if (s[i] == s[i - 1]) {
cur_len++; // 如果当前字符与前一个字符相同,则当前连续子串长度加1
}
else {
int idx = s[i - 1] - 'A'; // 计算当前字符在字母表中的索引(A为0,B为1,...,Z为25)
max_lengths[idx] = max(max_lengths[idx], cur_len); // 更新对应字符的最长连续子串长度
cur_len = 1; // 重置当前连续子串长度为1
}
}
// 处理最后一个字符的情况
int last_idx = s[len - 1] - 'A'; // 计算最后一个字符在字母表中的索引
max_lengths[last_idx] = max(max_lengths[last_idx], cur_len); // 更新最后一个字符的最长连续子串长度
// 对max_lengths数组进行降序排序,以便找到第 k 长的子串长度
sort(max_lengths.begin(), max_lengths.end(), greater<int>());
// 输出第 k 长的子串长度
if (k > 26 || max_lengths[k - 1] == 0||k == -1) {
cout << -1 << endl; // 如果 k 超过了字母总数或者第 k 长的子串长度为0,则输出 -1
}
else {
cout << max_lengths[k - 1] << endl;
}
return 0;
}
数组连续和m
#include <iostream>
#include <vector>
using namespace std;
int n, x;
long long res;
int main() {
cin >> n >> x;
vector<int> nums(n);
for (int i = 0; i < n; i++) cin >> nums[i];
if(x == 0 ) cout << n * (n + 1 ) / 2 << endl;
else
{
for (int i = 0, j = 0, sum = 0; i < n; i++)
{
sum += nums[i];
while (sum >= x)
{
res += n - i;
sum -= nums[j++];
}
}
cout << res << endl;
}
return 0;
}
小明的幸运数m
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
if(n < -100 || n > 100 || m < -100 || m > 100){
cout << 12345;
return 0;
}
vector<int> res(n + 1, 0);
for(int i = 1; i < n + 1; ++i){
int num;
cin >> num;
if(num < -100 || num > 100){
cout << 12345;
return 0;
}
if(num == m){
int offset = abs(num) + 1;
if(num > 0){
res[i] = res[i - 1] + offset;
}
else{
res[i] = res[i - 1] - offset;
}
}
else{
res[i] = res[i - 1] + num;
}
}
sort(res.begin(), res.end(), greater<int>());
cout << res[0];
}
悄悄话m
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void dfs(int x, vector<int>& nums, vector<int>& res) {
int left = 2 * x + 1;
int right = 2 * x + 2;
if (left < nums.size() && nums[left] != -1) {
res[left] = res[x] + nums[left];
dfs(left, nums, res);
}
if (right < nums.size() && nums[right] != -1) {
res[right] = res[x] + nums[right];
dfs(right, nums, res);
}
return;
}
int main() {
vector<int> nums;
int num;
while (cin >> num) {
nums.push_back(num);
}
int n = nums.size();
vector<int> res(n, 0);
res[0] = nums[0];
dfs(0, nums, res);
sort(res.begin(), res.end());
cout << res[n - 1];
}
CPU算力分配m
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main(){
int m, n;
cin >> m >> n;
vector<int> a(m);
vector<int> b(n);
for(int i = 0; i < m; ++i){
cin >> a[i];
}
for(int i = 0; i < n; ++i){
cin >> b[i];
}
sort(a.begin(), a.end());
int suma = accumulate(a.begin(), a.end(), 0);
int sumb = accumulate(b.begin(), b.end(), 0);
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(suma - sumb == 2 * (a[i] - b[j])){
cout << a[i] << " " << b[j];
return 0;
}
}
}
}
分披萨m
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
long recursion(int l, int r, vector<int> pizza, vector<vector<long>>& cache){
if(pizza[l] < pizza[r]){
r = r + 1;
if(r >= pizza.size()){
r = 0;
}
}
else{
l = l - 1;
if(l < 0){
l = pizza.size() - 1;
}
}
if(cache[l][r] > 0){
return cache[l][r];
}
if(l == r){
cache[l][r] = pizza[l];
}
else{
int newl = l - 1;
int newr = r + 1;
if(newl < 0){
newl = pizza.size() - 1;
}
if(newr >= pizza.size()){
newr = 0;
}
cache[l][r] = max(recursion(newl, r, pizza, cache) + pizza[l], recursion(l, newr, pizza, cache) + pizza[r]);
}
return cache[l][r];
}
int main(){
int n;
cin >> n;
vector<int> pizza(n);
vector<vector<long>> cache(n, vector<long>(n));
for(int i = 0; i < n; ++i){
cin >> pizza[i];
}
long res = 0;
for(int i = 0; i < n; ++i){
int l = i - 1;
if(l < 0){
l = pizza.size() - 1;
}
int r = i + 1;
if(r >= pizza.size()){
r = 0;
}
res = max(res, recursion(l, r, pizza, cache) + pizza[i]);
}
cout << res;
}
机场航班调度程序m
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(){
string s;
cin >> s;
stringstream ss(s);
vector<string> flights;
string flight;
while(getline(ss, flight, ',')){
flights.push_back(flight);
}
sort(flights.begin(), flights.end());
cout << flights[0];
for(int i = 1; i < flights.size(); ++i){
cout << "," << flights[i];
}
}
攀登者1m
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(){
string s;
cin >> s;
stringstream ss(s);
string num;
vector<int> nums;
while(getline(ss, num, ',')){
nums.push_back(stoi(num));
}
int n = nums.size();
int res = 0;
for(int i = 1; i < n - 1; ++i){
if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1]){
res++;
}
}
if(nums[0] > nums[1]){
res++;
}
if(nums[n - 1] > nums[n - 2]){
res++;
}
cout << res;
}
生成哈夫曼树m
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct node{
node *left;
node *right;
int weight;
int height;
};
struct cmp{
bool operator()(node *a, node *b){
if(a->weight != b->weight){
return a->weight > b->weight;
}
else{
return a->height > b->height;
}
}
};
void midorder(node *root){
if(root->left != nullptr){
midorder(root->left);
}
cout << root->weight << " ";
if(root->right != nullptr){
midorder(root->right);
}
}
int main(){
int n;
cin >> n;
priority_queue<node*, vector<node*>, cmp> pq;
for(int i = 0; i < n; ++i){
int w;
cin >> w;
node *v = new node{nullptr, nullptr, w, 0};
pq.push(v);
}
while(pq.size() > 1){
node *l = pq.top();
pq.pop();
node *r = pq.top();
pq.pop();
int newweight = l->weight + r->weight;
int newheight = max(l->height, r->height) + 1;
node *newnode = new node{l, r, newweight, newheight};
pq.push(newnode);
}
node *root = pq.top();
midorder(root);
}
密码解密m
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.length();
vector<int> res;
for (int i = 0; i < n; ++i) {
if (i + 2 < n && s[i + 2] == '*') {
string str = s.substr(i, 2);
res.push_back(stoi(str));
i = i + 2;
}
else {
string str = s.substr(i, 1);
res.push_back(stoi(str));
}
}
for (int i = 0; i < res.size(); ++i) {
int k = res[i];
char ch = (char)(k - 1 + 'a');
cout << ch;
}
}
来自异国的客人m
#include <iostream> // 用于输入输出
using namespace std;
int main(void) {
long long k, n, m;
cin >> k >> n >> m; // 输入 k, n, m
int ans = 0; // 结果计数初始化为 0
while (k) {
ans += (k % m == n); // 判断 k 除以 m 的余数是否等于 n,符合则计数加 1
k /= m; // 更新 k,除以 m
}
cout << ans << endl; // 输出结果
return 0;
}
求幸存数之和m
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s;
cin >> s;
stringstream ss(s);
string token;
vector<int> nums;
while (getline(ss, token, ',')) {
nums.push_back(stoi(token));
}
int jump, left;
cin >> jump >> left;
if(left == 0){
cout << 0;
return 0;
}
int i = (jump + 1) % nums.size();
while (nums.size() > left) {
nums.erase(nums.begin() + i);
i = (i + jump) % nums.size();
}
cout << accumulate(nums.begin(), nums.end(), 0);
}
会议室占用时间m
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
vector<pair<int, int>> vec;
for(int i = 0; i < n; ++i){
int a, b;
cin >> a >> b;
vec.push_back(make_pair(a, b));
}
sort(vec.begin(), vec.end(), [](pair<int, int> a, pair<int, int> b){
if(a.first == b.first){
return a.second < b.second;
}
else{
return a.first < b.first;
}
});
int start = vec[0].first;
int end = vec[0].second;
vector<pair<int, int>> res;
for(int i = 1; i < vec.size(); ++i){
if(vec[i].first > end){
res.push_back(make_pair(start, end));
start = vec[i].first;
end = vec[i].second;
}
else{
end = max(end, vec[i].second);
}
}
res.push_back(make_pair(start, end));
for(int i = 0; i < res.size(); ++i){
cout << res[i].first << " " << res[i].second << endl;
}
}
手机App防沉迷系统m
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct app {
string name;
int priority;
int starttime;
int endtime;
};
int main() {
int n;
cin >> n;
vector<app> apps;
for (int i = 0; i < n; ++i) {
string s1, s2, s3, s4;
cin >> s1 >> s2 >> s3 >> s4;
app tempapp;
tempapp.name = s1;
tempapp.priority = stoi(s2);
string hour = s3.substr(0, 2);
string miniute = s3.substr(3, 2);
tempapp.starttime = (stoi(hour) * 60 + stoi(miniute));
hour = s4.substr(0, 2);
miniute = s4.substr(3, 2);
tempapp.endtime = (stoi(hour) * 60 + stoi(miniute));
apps.push_back(tempapp);
}
string time;
cin >> time;
stable_sort(apps.begin(), apps.end(), [](app a, app b) {
return a.priority > b.priority;
});
vector<app> res;
res.push_back(apps[0]);
for (int i = 1; i < apps.size(); ++i) {
int j = 0;
for (; j < res.size(); ++j) {
if (res[j].starttime >= apps[i].starttime && res[j].starttime < apps[i].endtime) {
break;
}
if (res[j].endtime <= apps[i].endtime && res[j].endtime > apps[i].starttime) {
break;
}
}
if (j == res.size()) {
res.push_back(apps[i]);
}
}
string hour = time.substr(0, 2);
string miniute = time.substr(3, 2);
int t = (stoi(hour) * 60 + stoi(miniute));
for (int i = 0; i < res.size(); ++i) {
if (t >= res[i].starttime && t < res[i].endtime) {
cout << res[i].name;
return 0;
}
}
cout << "NA";
}
小朋友来自多少小区m
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main(){
int n;
map<int, int> garden;
while(cin >> n){
if(garden.find(n) == garden.end()){
garden[n] = 1;
}
else{
garden[n]++;
}
}
int res = 0;
for(auto it = garden.begin(); it != garden.end(); ++it){
int num = it->first;
int count = it->second;
int k = count / (num + 1);
if(count % (num + 1) == 0){
res += k * (num + 1);
}
else{
res += (k + 1) * (num + 1);
}
}
cout << res;
}
精准核酸检测v
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue> // 包含队列库
using namespace std;
// 将字符串s按照字符ch进行分割,并返回分割后的整数数组
vector<int> split(const string& s, char ch) {
stringstream ss(s); // 使用字符串流来处理字符串
string token; // 存储分割后的每个子字符串
vector<int> res; // 存储分割后的整数数组
while (getline(ss, token, ch)) { // 按照指定字符分割字符串
res.push_back(stoi(token)); // 将分割后的子字符串转换为整数并存入结果数组
}
return res; // 返回分割后的整数数组
}
// 使用BFS找到所有与节点x相连的节点,并标记它们
void bfs(int x, const vector<vector<int>>& grid, vector<bool>& visited) {
queue<int> q; // 队列用于广度优先搜索
q.push(x); // 将起始节点x入队
visited[x] = true; // 标记起始节点x为已访问
while (!q.empty()) { // 当队列不为空时
int node = q.front(); // 取出队首节点
q.pop(); // 移除队首节点
for (int y = 0; y < grid.size(); ++y) { // 遍历所有节点
if (grid[node][y] == 1 && !visited[y]) { // 如果节点node与节点y相连且节点y未被访问
q.push(y); // 将节点y入队
visited[y] = true; // 标记节点y为已访问
}
}
}
}
int main() {
int n; // 变量n表示节点数
cin >> n; // 输入节点数
string s; // 存储感染者节点编号的字符串
cin >> s; // 输入感染者节点编号字符串
vector<int> ill = split(s, ','); // 将感染者节点编号字符串分割为整数数组
vector<vector<int>> grid(n); // 邻接矩阵表示的图
for (int i = 0; i < n; ++i) {
string str; // 存储每行输入的邻接矩阵字符串
cin >> str; // 输入邻接矩阵字符串
grid[i] = split(str, ','); // 将字符串分割为整数数组并存入邻接矩阵
}
vector<bool> infected(n, false); // 标记节点是否为感染者
for (int i : ill) {
infected[i] = true; // 将感染者节点标记为true
}
int count = 0; // 统计未感染节点数量
vector<bool> visited(n, false); // 标记节点是否被访问过
for (int i : ill) { // 遍历所有感染者节点
if (!visited[i]) { // 如果感染者节点未被访问
bfs(i, grid, visited); // 进行BFS遍历
}
}
for (int i = 0; i < n; ++i) { // 遍历所有节点
if (visited[i] && !infected[i]) { // 如果节点i被访问且未被感染
count++; // 统计未感染节点数量
}
}
cout << count; // 输出结果
}
多段线数据压缩m
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main(){
int x, y;
vector<pair<int, int>> vec;
while(cin >> x >> y){
vec.push_back(make_pair(x, y));
}
vector<pair<int, int>> res;
res.push_back(vec[0]);
for(int i = 1; i < vec.size() - 1; ++i){
pair<int, int> n1 = vec[i - 1];
pair<int, int> n2 = vec[i];
pair<int, int> n3 = vec[i + 1];
if(n2.first == n1.first && n2.first == n3.first){
continue;
}
if(n2.second == n1.second && n2.second == n3.second){
continue;
}
if(n2.second != n1.second && n3.second != n2.second){
int k1 = (n2.first - n1.first) / (n2.second - n1.second);
int k2 = (n3.first - n2.first) / (n3.second - n2.second);
if((k1 == 1 && k2 == 1) || (k1 == -1 && k2 == -1)){
continue;
}
}
res.push_back(n2);
}
res.push_back(vec[vec.size() - 1]);
for(int i = 0; i < res.size(); ++i){
cout << res[i].first << " " << res[i].second << " ";
}
}
测试用例执行计划m
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
vector<int> split(string s, char ch) {
stringstream ss(s);
string token;
vector<int> res;
while (getline(ss, token, ch)) {
res.push_back(stoi(token));
}
return res;
}
int main() {
int n, m;
cin >> n >> m;
vector<int> character(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> character[i];
}
vector<pair<int, int>> p;
string s;
getline(cin, s);
for (int i = 1; i <= m; ++i) {
getline(cin, s);
vector<int> vec = split(s, ' ');
int sum = 0;
for (int j = 0; j < vec.size(); ++j) {
sum += character[vec[j]];
}
p.push_back(make_pair(i, sum));
}
sort(p.begin(), p.end(), [](pair<int, int> a, pair<int, int> b){
if(a.second == b.second){
return a.first < b.first;
}
else{
return a.second > b.second;
}
});
for(int i = 0; i < m; ++i){
cout << p[i].first << endl;
}
}
堆内存申请m
#include <cstdlib>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
int a, b;
int k = 100;
int res = -1;
vector<pair<int, int>> vec;
while (cin >> a >> b) {
vec.push_back(make_pair(a, b));
}
int len = vec[0].first;
if (len >= n) {
if (len - n < k) {
k = len - n;
res = 0;
}
}
for (int i = 1; i < vec.size(); ++i) {
int preindex = vec[i - 1].first;
int preoffset = vec[i - 1].second;
int currentindex = vec[i].first;
len = currentindex - (preindex + preoffset);
if (len >= n) {
if (len - n < k) {
k = len - n;
res = preindex + preoffset;
}
}
}
int size = vec.size();
len = 100 - vec[size - 1].first - vec[size - 1].second;
if (len >= n) {
if (len - n < k) {
k = len - n;
res = vec[size - 1].first + vec[size - 1].second;;
}
}
cout << res;
}
灰度图存储m
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main() {
int row, col;
cin >> row >> col;
int a, b;
vector<pair<int, int>> vec;
while (cin >> a >> b) {
vec.push_back(make_pair(a, b));
}
pair<int, int> p = vec.back();
vec.pop_back();
int index = p.first * col + p.second;
int currentindex = -1;
for (int i = 0; i < vec.size(); ++i) {
currentindex += vec[i].second;
if (currentindex >= index) {
cout << vec[i].first;
break;
}
}
}
火星文计算2m
#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <cstdlib>
using namespace std;
long long sharp(long long x, long long y) {
return 4 * x + 3 * y + 2;
}
long long dollar(long long x, long long y) {
return 2 * x + y + 3;
}
void solve_method(const string& input) {
// 使用正则表达式来提取操作符和数字
regex num_regex("\\d+");
regex op_regex("[#$]");
// 提取所有操作符和数字
vector<string> operators;
vector<long long> nums;
auto num_begin = sregex_iterator(input.begin(), input.end(), num_regex);
auto num_end = sregex_iterator();
for (sregex_iterator i = num_begin; i != num_end; ++i) {
nums.push_back(stoll((*i).str()));
}
auto op_begin = sregex_iterator(input.begin(), input.end(), op_regex);
auto op_end = sregex_iterator();
for (sregex_iterator i = op_begin; i != op_end; ++i) {
operators.push_back((*i).str());
}
// 处理#运算
auto pos_s = find(operators.begin(), operators.end(), "#");
while (pos_s != operators.end()) {
int index = distance(operators.begin(), pos_s);
nums[index] = sharp(nums[index], nums[index + 1]);
nums.erase(nums.begin() + index + 1);
operators.erase(pos_s);
pos_s = find(operators.begin(), operators.end(), "#");
}
// 处理$运算
long long res = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
res = dollar(res, nums[i]);
}
cout << res << endl;
}
int main() {
string input_str;
getline(cin, input_str); // 读取整行输入
solve_method(input_str); // 调用求解方法
return 0;
}
数组去重和排序v
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <algorithm>
using namespace std;
int main() {
// 读取输入字符串
string input;
getline(cin, input);
// 将输入字符串按逗号分割,并转换为整数数组
stringstream ss(input);
string temp;
vector<int> nums;
while (getline(ss, temp, ',')) {
nums.push_back(stoi(temp));
}
// 使用哈希表统计每个数字出现的频次
unordered_map<int, int> freqMap;
for (int num : nums) {
freqMap[num]++;
}
// 创建一个新的向量,包含原数组中的每个数字及其频次,但只保留第一次出现的数字
vector<pair<int, int>> freqList;
unordered_set<int> seen;
for (int num : nums) {
if (seen.find(num) == seen.end()) {
freqList.push_back({num, freqMap[num]});
seen.insert(num);
}
}
// 按照频次降序排序,如果频次相同则保持原始顺序(stable_sort 保持相对顺序)
stable_sort(freqList.begin(), freqList.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second; // 按频次降序排序
});
// 输出结果
for (size_t i = 0; i < freqList.size(); ++i) {
cout << freqList[i].first;
if (i != freqList.size() - 1) {
cout << ",";
}
}
cout << endl;
return 0;
}
求字符串中所有整数的最小和x
#include <iostream>
#include <string>
#include <cstdlib>
int main() {
std::string s;
std::getline(std::cin, s);
bool isNegative = false;
std::string negative;
long long ans = 0;
for (char c : s) {
if (isdigit(c)) {
if (isNegative) {
negative += c;
} else {
ans += c - '0';
}
} else {
if (isNegative && !negative.empty()) {
ans -= std::atoll(negative.c_str());
negative.clear();
}
isNegative = (c == '-');
}
}
if (!negative.empty()) {
ans -= std::atoll(negative.c_str());
}
std::cout << ans << std::endl;
return 0;
}
求满足条件的最长子串的长度/
#include <iostream>
#include <string>
#include <deque>
#include <algorithm> // for std::max
using namespace std;
int main() {
// 使用std::string替代char数组,进行字符串输入
string s;
getline(cin, s);
int maxLen = -1; // 用于存储最长子串长度
bool hasLetter = false; // 检查是否包含字母
int l = 0, r = 0; // 双指针,用于滑动窗口
deque<int> letterIdx; // 使用std::deque替代链表,存储字母索引
int len = s.length();
while (r < len) {
char c = s[r];
// 检查字符是否是字母
if (isalpha(c)) {
hasLetter = true;
letterIdx.push_back(r);
// 如果字母数量超过1,将左指针移动到最前字母的下一个位置
if (letterIdx.size() > 1) {
l = letterIdx.front() + 1;
letterIdx.pop_front();
}
// 如果左右指针重合,右指针右移
if (r == l) {
r++;
continue;
}
}
// 更新最大长度
maxLen = max(maxLen, r - l + 1);
r++;
}
// 如果没有字母,输出-1,否则输出最大长度
if (!hasLetter) {
cout << "-1" << endl;
} else {
cout << maxLen << endl;
}
return 0;
}
字符串分割(二)/
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
// 转换函数:根据字母大小写的数量决定转换方式
string convert(const string& s) {
int lowerCount = 0;
int upperCount = 0;
// 统计小写字母和大写字母的数量
for (char c : s) {
if (islower(c)) {
lowerCount++;
} else if (isupper(c)) {
upperCount++;
}
}
// 根据统计结果决定转换方式
if (lowerCount > upperCount) {
string result = s;
transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
} else if (lowerCount < upperCount) {
string result = s;
transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
} else {
return s;
}
}
// 主函数:处理输入和输出
int main() {
int k;
string s;
// 获取输入
cin >> k;
cin.ignore(); // 忽略换行符
getline(cin, s);
// 分割输入字符串
vector<string> arr;
size_t pos = 0;
while ((pos = s.find('-')) != string::npos) {
arr.push_back(s.substr(0, pos));
s.erase(0, pos + 1);
}
arr.push_back(s);
vector<string> ans;
// 第一个子串不需要转换大小写,直接加入结果
ans.push_back(arr[0]);
// 合并剩余子串并进行处理
string newStr;
for (size_t i = 1; i < arr.size(); ++i) {
newStr += arr[i];
}
// 按照每k个字符分组并转换大小写
for (size_t i = 0; i < newStr.length(); i += k) {
string subStr = newStr.substr(i, k);
ans.push_back(convert(subStr));
}
// 输出结果
for (size_t i = 0; i < ans.size(); ++i) {
cout << ans[i];
if (i != ans.size() - 1) {
cout << "-";
}
}
cout << endl;
return 0;
}
英文输入法m
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string str, pre;
getline(cin, str);
getline(cin, pre);
stringstream ss(str);
string word;
vector<string> words;
while (getline(ss, word, ' ')) {
words.push_back(word);
}
vector<string> res;
for (int i = 0; i < words.size(); ++i) {
string temp = "";
int j = 0;
while (j < words[i].size()) {
while ((words[i][j] >= 'A' && words[i][j] <= 'Z') || (words[i][j] >= 'a' && words[i][j] <= 'z')) {
temp += words[i][j];
j++;
}
j++;
if (pre == temp.substr(0, pre.size()) && find(res.begin(), res.end(), temp) == res.end()) {
res.push_back(temp);
}
temp = "";
}
}
if (res.size() == 0) {
cout << pre;
}
else {
sort(res.begin(), res.end());
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << " ";
}
}
}
字符串筛选排序/
#include <iostream>
#include <string>
#include <algorithm> // for std::sort
using namespace std;
int main() {
string s, s1;
int k;
cin >> s >> k;
s1 = s;
sort(s1.begin(), s1.end());
int n = s.size();
k = min(k, n); // 确保 k 不超过字符串长度
char ch = s1[k - 1]; // 找到第 k 小的字符
for (int i = 0; i < n; i++) {
if (s[i] == ch) {
cout << i << endl; // 输出位置
break;
}
}
return 0;
}
连续字母长度/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
int k;
cin >> s >> k; // 输入字符串 s 和整数 k
vector<int> max_lengths(26, 0); // 存储每个字母的最长连续子串长度,初始化为0,共有26个字母
int len = s.size(); // 获取字符串 s 的长度
int cur_len = 1; // 当前连续子串长度的计数器,默认为1(至少包含当前字符)
// 遍历字符串 s,找到每个字符的最长连续子串长度
for (int i = 1; i < len; ++i) {
if (s[i] == s[i - 1]) {
cur_len++; // 如果当前字符与前一个字符相同,则当前连续子串长度加1
}
else {
int idx = s[i - 1] - 'A'; // 计算当前字符在字母表中的索引(A为0,B为1,...,Z为25)
max_lengths[idx] = max(max_lengths[idx], cur_len); // 更新对应字符的最长连续子串长度
cur_len = 1; // 重置当前连续子串长度为1
}
}
// 处理最后一个字符的情况
int last_idx = s[len - 1] - 'A'; // 计算最后一个字符在字母表中的索引
max_lengths[last_idx] = max(max_lengths[last_idx], cur_len); // 更新最后一个字符的最长连续子串长度
// 对max_lengths数组进行降序排序,以便找到第 k 长的子串长度
sort(max_lengths.begin(), max_lengths.end(), greater<int>());
// 输出第 k 长的子串长度
if (k > 26 || max_lengths[k - 1] == 0||k == -1) {
cout << -1 << endl; // 如果 k 超过了字母总数或者第 k 长的子串长度为0,则输出 -1
}
else {
cout << max_lengths[k - 1] << endl;
}
return 0;
}
拼接URL/
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s; // 读取输入字符串
size_t pos = s.find(','); // 查找','的位置
string pre = (pos == string::npos) ? s : s.substr(0, pos); // 获取前缀
string suf = (pos == string::npos) ? "" : s.substr(pos + 1); // 获取后缀
// 处理前缀
if (pre.back() != '/') {
pre.push_back('/');
}
if (suf.front() == '/') {
suf = suf.substr(1);
}
// 合并前缀和后缀
string res = pre + suf;
// 移除前缀和后缀之间的多余的 '/'
if (pre.back() == '/' && suf.front() == '/') {
while(pre.back() == '/') pre.pop_back();
while(suf[1] == '/') suf.substr(1);
res = pre + suf;
}
// 输出结果
cout << res << endl;
return 0;
}
字符串序列判定x
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
int now =0, pos = -1;
for (int i = 0; i < t.length(); i++) {
if (t[i] == s[now]) now++;
if (now == s.length()) {
pos = i;
break;
}
}
cout << pos << endl;
return 0;
}
最长的指定瑕疵度的元音子串m
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int flaw;
cin >> flaw;
string s;
cin >> s;
int n = s.size();
string str = "aeiouAEIOU";
vector<int> idx;
for (int i = 0; i < n; ++i) {
if (str.find(s[i]) != -1) {
idx.push_back(i);
}
}
int res = 0;
int l = 0;
int r = 0;
while (r < idx.size()) {
int count = (idx[r] - idx[l]) - (r - l);
if (count < flaw) {
r++;
}
else if (count > flaw) {
l++;
}
else {
res = max(res, idx[r] - idx[l] + 1);
r++;
}
}
cout << res;
}
考勤信息/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <sstream>
using namespace std;
// 定义考勤信息映射
unordered_map<string, int> mp = {{"absent", 0}, {"late", 1}, {"leaveearly", 2}, {"present", 3}};
// 检查考勤信息是否合法的函数
bool check(const vector<string>& s) {
int n = s.size();
int absents = 0, presents = 0;
vector<int> status(4, 0); // 用于记录窗口内的考勤状态计数
// 遍历考勤信息
for (int i = 0; i < n; ++i) {
status[mp[s[i]]]++; // 更新当前状态的计数
if (mp[s[i]] == 0) absents++; // 更新缺勤计数
if (mp[s[i]] == 3) presents++; // 更新出勤计数
// 保持窗口大小为7
if (i >= 7) {
status[mp[s[i - 7]]]--; // 移出窗口的状态计数减少
if (mp[s[i - 7]] == 3) presents--; // 更新出勤计数
}
// 检查窗口内是否有4天以上出勤
if (i >= 6 && presents < 4) return false;
// 检查连续两天迟到或早退
if (i > 0 && 1 <= mp[s[i]] && mp[s[i]] <= 2 && 1 <= mp[s[i - 1]] && mp[s[i - 1]] <= 2) {
return false;
}
}
// 检查总的缺勤次数
return absents <= 1;
}
int main() {
int n;
cin >> n;
cin.ignore(); // 消耗掉换行符
// 处理每个测试用例
for (int i = 0; i < n; ++i) {
string line;
getline(cin, line);
vector<string> s;
stringstream ss(line);
string word;
// 使用 stringstream 分割字符串得到考勤信息
while (ss >> word) {
s.push_back(word);
}
// 调用 check 函数检查考勤信息是否合法,并输出结果
cout << (check(s) ? "true" : "false") << ' ';
}
return 0;
}
字符串变换最小字符串/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MAX_SIZE 1000
string getResult(string s);
// 比较函数,用于排序
bool cmp(char a, char b) {
return a < b;
}
int main() {
string s;
getline(cin, s); // 从标准输入读取一行字符串,保存到 s 中
int len = s.length(); // 获取字符串长度
string minS = s; // 复制字符串
sort(minS.begin(), minS.end(), cmp); // 对字符串进行排序
// 如果排序后的字符串与原字符串相同,直接返回原字符串
if (minS == s) {
cout << s;
}
else
{
for (int i = 0; i < len; i++) {
if (s[i] != minS[i]) {
// 找到第一个不同的字符位置
auto swapIdx = s.find_last_of(minS[i]); // 找到最后一个出现的位置
swap(s[i], s[swapIdx]); // 交换字符
break;
}
}
cout << s;
}
return 0;
}
查找接口成功率最优时间段v
#include <iostream>
#include <vector>
#include <deque> // 用于滑动窗口
#include <sstream> // 用于将结果转换为字符串
#include <algorithm>
using namespace std;
int main() {
int minAverageLost; // 输入的最小平均损失
cin >> minAverageLost;
vector<int> nums; // 存储输入的数字
int num;
// 读取所有输入的数字
while (cin >> num) {
nums.push_back(num);
}
int n = nums.size();
if (n == 0) {
cout << "NULL" << endl;
return 0;
}
vector<int> preSum(n + 1, 0); // 前缀和数组,初始化为0
// 计算前缀和
for (int i = 1; i <= n; ++i) {
preSum[i] = preSum[i - 1] + nums[i - 1];
}
vector<pair<int, int>> arrList; // 存储满足条件的区间
int maxLen = 0; // 最大区间长度
// 滑动窗口寻找所有符合条件的区间
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j <= n; ++j) {
int sum = preSum[j] - preSum[i]; // 区间 [i, j-1] 的和
int len = j - i; // 区间长度
int lost = len * minAverageLost; // 计算损失
// 如果区间和小于等于损失
if (sum <= lost) {
if (len > maxLen) {
// 如果发现更长的区间,清空之前的区间记录
arrList.clear();
maxLen = len;
}
if (len == maxLen) {
// 记录当前区间
arrList.push_back({i, j - 1});
}
}
}
}
// 输出结果
if (arrList.empty()) {
cout << "NULL" << endl;
} else {
// 排序区间
sort(arrList.begin(), arrList.end());
// 将结果格式化为字符串
stringstream oss;
for (const auto& interval : arrList) {
oss << interval.first << "-" << interval.second << " ";
}
// 去掉末尾的空格
string result = oss.str();
result.pop_back();
cout << result << endl;
}
return 0;
}
执行时长
#include <iostream>
using namespace std;
int m, n,ans, remain;
int main() {
cin >> m >> n;
int nums[n];
for (int i = 0; i < n; i++) cin >> nums[i];
for (auto x : nums) {
if (remain + x <= m) remain = 0;
else remain += x - m;
ans++;
}
ans += (remain + m - 1) / m; // 上取整
cout << ans << endl;
return 0;
}
查找众数及中位数v
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> w;
int x;
while (cin >> x) {
w.push_back(x);
}
// 找出最大和最小值
int minVal = *min_element(w.begin(), w.end());
int maxVal = *max_element(w.begin(), w.end());
// 计数数组大小
int range = maxVal - minVal + 1;
vector<int> count(range, 0);
// 统计每个值的出现次数
for (int num : w) {
count[num - minVal]++;
}
// 找出出现频率最高的次数
int maxCnt = *max_element(count.begin(), count.end());
// 找出所有出现频率最高的值
vector<int> num;
for (int i = 0; i < range; i++) {
if (count[i] == maxCnt) {
num.push_back(i + minVal);
}
}
// 排序并计算中位数
sort(num.begin(), num.end());
int n = num.size();
if (n % 2 == 1) {
cout << num[n / 2] << endl;
} else {
cout << (num[n / 2] + num[n / 2 - 1]) / 2 << endl;
}
return 0;
}
最大N个数与最小N个数的和v
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
int m;
cin >> m; // 读取元素个数
vector<int> w(m);
for (int i = 0; i < m; i++) {
cin >> w[i]; // 读取每个元素
}
int n;
cin >> n; // 读取需要计算的最小和最大元素个数
if (n < 0) {
cout << -1 << endl;
return 0;
}
// 使用 unordered_set 去重
unordered_set<int> us(w.begin(), w.end());
w.assign(us.begin(), us.end()); // 将 unordered_set 元素重新赋值给向量
sort(w.begin(), w.end()); // 排序
m = w.size(); // 更新去重后的元素个数
// 检查条件是否满足
if (m < 2 * n || w[0] < 0 || w[m - 1] > 1000) {
cout << -1 << endl; // 不满足条件输出 -1
} else {
// 计算最小的 n 个数的和
int sum_min = accumulate(w.begin(), w.begin() + n, 0);
// 计算最大的 n 个数的和
int sum_max = accumulate(w.end() - n, w.end(), 0);
// 输出结果
cout << sum_min + sum_max << endl;
}
return 0;
}
整数对最小和v
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int size1, size2, k;
// 读取数组1的大小和元素
cin >> size1;
vector<int> nums1(size1);
for (int i = 0; i < size1; ++i) {
cin >> nums1[i];
}
// 读取数组2的大小和元素
cin >> size2;
vector<int> nums2(size2);
for (int i = 0; i < size2; ++i) {
cin >> nums2[i];
}
// 读取需要的最小和的个数
cin >> k;
// 计算所有可能的和
vector<int> pairs;
for (int i = 0; i < size1; ++i) {
for (int j = 0; j < size2; ++j) {
pairs.push_back(nums1[i] + nums2[j]);
}
}
// 排序所有的和
sort(pairs.begin(), pairs.end());
// 计算前k个最小和的总和
int total_sum = 0;
for (int i = 0; i < k; ++i) {
total_sum += pairs[i];
}
cout << total_sum << endl;
return 0;
}
靠谱的车v
#include <iostream>
#include <string>
#include <vector> // Include vector header for using vector
using namespace std;
int main() {
string w;
cin >> w;
int n = w.length();
long long ans = 0;
// Vector to store powers of 9
vector<long long> powers_of_9(n);
powers_of_9[0] = 1;
for (int i = 1; i < n; ++i) {
powers_of_9[i] = powers_of_9[i - 1] * 9;
}
for (int i = 0; i < n; ++i) {
int digit = w[i] - '0';
int cost = digit > 4 ? digit - 1 : digit;
ans += cost * powers_of_9[n - i - 1];
}
cout << ans << endl;
return 0;
}
素数之积v
#include <iostream>
#include <cmath> // 用于sqrt函数
using namespace std;
// 函数声明
void getResult(int n);
bool isPrime(int n);
int main() {
int n;
cin >> n; // 读取输入的整数
getResult(n); // 调用函数处理结果
return 0;
}
// 获取结果函数
void getResult(int n) {
// 假设i为n的因子,从2开始到sqrt(n)
for (int i = 2; i <= sqrt(n); i++) {
// 如果n能整除i, 则i是n的因子
if (n % i == 0) {
// j为n的另一个因子
int j = n / i;
// 只有i和j都是素数时,n才是两个素数的乘积
if (isPrime(i) && isPrime(j)) {
if (i < j) {
cout << i << " " << j << endl;
} else {
cout << j << " " << i << endl;
}
return;
}
}
}
// 如果没有找到符合条件的因子对,输出-1 -1
cout << "-1 -1" << endl;
}
// 判断n是否为素数的函数
bool isPrime(int n) {
// 特殊情况处理:小于等于3的数中,只有大于1的数是素数
if (n <= 3) return n > 1;
// 如果n是偶数或能被3整除,则不是素数
if (n % 2 == 0 || n % 3 == 0) return false;
// 从5开始检查因子,并跳过6的倍数
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true; // 其他情况,n是素数
}
用连续自然数之和来表达整数v
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void getResult(int t);
int main() {
int t;
cin >> t; // 获取输入的整数 t
getResult(t); // 调用算法入口函数
return 0;
}
void getResult(int t) {
vector<vector<int>> ans; // 用于存储结果的二维数组
// 使用双指针法寻找所有满足条件的子数组
for (int start = 1; start <= t / 2 + 1; ++start) {
int sum = 0;
vector<int> sequence;
for (int num = start; sum < t; ++num) {
sum += num;
sequence.push_back(num);
if (sum == t) {
ans.push_back(sequence);
break;
}
}
}
// 单独处理 t 自身为一项的情况
ans.push_back(vector<int>{t});
// 按子数组长度进行排序
sort(ans.begin(), ans.end(), [](const vector<int>& a, const vector<int>& b) {
return a.size() < b.size();
});
// 输出结果
for (const auto& an : ans) {
cout << t << "=" << an[0];
for (size_t i = 1; i < an.size(); ++i) {
cout << "+" << an[i];
}
cout << endl;
}
// 输出总的结果数量
cout << "Result:" << ans.size() << endl;
}
火星文计算
#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include <sstream>
int getResult(const std::string& s) {
std::regex re("(\\d+)\\$(\\d+)");
std::string input = s;
std::smatch match;
while (std::regex_search(input, match, re)) {
std::string subS = match.str(0);
int x = std::stoi(match.str(1));
int y = std::stoi(match.str(2));
std::string replacement = std::to_string(3 * x + y + 2);
input = std::regex_replace(input, re, replacement, std::regex_constants::format_first_only);
}
// Split the string by '#'
std::vector<int> arr;
std::stringstream ss(input);
std::string item;
while (std::getline(ss, item, '#')) {
arr.push_back(std::stoi(item));
}
// Perform the final calculation
int x = arr[0];
for (size_t i = 1; i < arr.size(); ++i) {
int y = arr[i];
x = 2 * x + 3 * y + 4;
}
return x;
}
int main() {
std::string s;
std::getline(std::cin, s);
std::cout << getResult(s) << std::endl;
return 0;
}
寻找身高相近的小朋友v
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath> // 用于abs函数
using namespace std;
int main() {
int h, n;
cin >> h >> n; // 输入h和n
vector<int> heights(n);
for (int i = 0; i < n; ++i) {
cin >> heights[i]; // 输入每个高度
}
// 排序函数,按绝对差值和值本身排序
sort(heights.begin(), heights.end(), [h](int a, int b) {
int diff_a = abs(a - h);
int diff_b = abs(b - h);
return (diff_a == diff_b) ? (a < b) : (diff_a < diff_b);
});
// 输出结果
for (int i = 0; i < n; ++i) {
cout << heights[i];
if (i < n - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
整型数组按个位值排序v
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
// 自定义排序函数,用于按最后一个字符排序,若相同则按原始顺序排序
bool compare(const pair<string, int>& a, const pair<string, int>& b) {
if (a.first.back() != b.first.back())
return a.first.back() < b.first.back();
return a.second < b.second;
}
int main() {
// 读取输入的一整行字符串
string input;
getline(cin, input);
// 用于存储字符串和它们在原始输入中的位置的向量
vector<pair<string, int>> w;
// 使用istringstream分割输入字符串
istringstream iss(input);
string token;
int cnt = 0;
while (getline(iss, token, ',')) {
w.push_back({token, cnt++});
}
// 按照最后一个字符排序,若相同则按原始顺序排序
sort(w.begin(), w.end(), compare);
// 输出排序后的字符串,逗号分隔
for (size_t i = 0; i < w.size(); ++i) {
cout << w[i].first;
if (i != w.size() - 1) {
cout << ",";
}
}
return 0;
}
按身高和体重排队v
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n; // 输入学生数量
vector<int> heights(n);
vector<int> weights(n);
vector<int> indices(n);
// 输入学生身高
for (int i = 0; i < n; ++i) {
cin >> heights[i];
indices[i] = i + 1; // 初始化索引为1到n
}
// 输入学生体重
for (int i = 0; i < n; ++i) {
cin >> weights[i];
}
// 自定义排序函数
auto cmp = [&](int a, int b) {
if (heights[a - 1] != heights[b - 1])
return heights[a - 1] < heights[b - 1];
if (weights[a - 1] != weights[b - 1])
return weights[a - 1] < weights[b - 1];
return a < b;
};
// 使用自定义排序函数进行排序
sort(indices.begin(), indices.end(), cmp);
// 构造输出字符串
string res;
for (int i = 0; i < n; ++i) {
res += to_string(indices[i]);
if (i < n - 1) {
res += " ";
}
}
// 输出结果
cout << res << endl;
return 0;
}
解密犯罪时间m
#include <algorithm>
#include <iostream>
#include <regex>
#include <set>
#include <string>
#include <vector>
using namespace std;
// 正则表达式,用于匹配有效的时间字符串
regex reg("(([01][0-9])|([2][0-3]))[0-5][0-9]");
// 深度优先搜索函数,生成所有可能的时间组合
void dfs(const vector<char>& arr, vector<char>& path, set<string>& res) {
if (path.size() == 4) { // 当路径长度为4时,构成一个时间字符串
string timeStr(path.begin(), path.end());
if (regex_search(timeStr, reg)) { // 检查时间字符串是否有效
res.insert(timeStr); // 将有效的时间字符串加入结果集合
}
return;
}
for (int i = 0; i < arr.size(); ++i) {
path.push_back(arr[i]);
dfs(arr, path, res);
path.pop_back(); // 回溯
}
}
// 主函数
string getResult(const string& hour, const string& minute) {
vector<char> arr(hour.begin(), hour.end());
arr.insert(arr.end(), minute.begin(), minute.end()); // 将小时和分钟字符加入数组
sort(arr.begin(), arr.end()); // 去重之前排序
arr.erase(unique(arr.begin(), arr.end()), arr.end()); // 去重
set<string> res;
vector<char> path;
dfs(arr, path, res); // 调用DFS函数
string currentTime = hour + minute;
auto it = res.find(currentTime); // 找到当前时间在结果集合中的位置
if (it == res.end() || next(it) == res.end()) { // 如果当前时间是最后一个
it = res.begin(); // 循环到第一个时间
} else {
it = next(it); // 否则选择下一个时间
}
string recentTime = *it;
recentTime.insert(2, ":"); // 在时间字符串中插入冒号
return recentTime;
}
int main() {
string input;
cin >> input;
size_t colonPos = input.find(":");
string hour = input.substr(0, colonPos); // 获取小时部分
string minute = input.substr(colonPos + 1); // 获取分钟部分
cout << getResult(hour, minute) << endl; // 输出结果
return 0;
}
数组连续和v
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 使用前缀和数组和二分查找的函数
long long countSubarraysWithSumAtLeastX(const vector<int>& nums, int x) {
int n = nums.size();
vector<long long> prefix_sum(n + 1, 0); // 前缀和数组,额外的一个位置用于处理前缀和为0的情况
// 计算前缀和
for (int i = 0; i < n; ++i) {
prefix_sum[i + 1] = prefix_sum[i] + nums[i];
}
long long result = 0;
// 对每一个前缀和,使用二分查找来找出满足条件的子数组
for (int i = 0; i < n; ++i) {
long long target = prefix_sum[i] + x;
// 使用二分查找来找到第一个大于等于target的前缀和的位置
auto it = lower_bound(prefix_sum.begin(), prefix_sum.end(), target);
// 计算满足条件的子数组数量
result += distance(it, prefix_sum.end());
}
return result;
}
int main() {
int n, x;
cin >> n >> x; // 输入数组长度和目标和
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i]; // 输入数组的每个元素
}
// 如果目标和为0,直接计算所有子数组数量
if (x == 0) {
long long total_subarrays = (long long)n * (n + 1) / 2;
cout << total_subarrays << endl;
} else {
// 计算结果并输出
cout << countSubarraysWithSumAtLeastX(nums, x) << endl;
}
return 0;
}
停车场车辆统计v
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main() {
string line;
vector<int> data;
// 读取整行输入
getline(cin, line);
stringstream ss(line);
char comma;
int value;
// 分割以逗号分隔的输入数据
while (ss >> value) {
data.push_back(value);
ss >> comma; // 读取逗号分隔符
}
int count = 0; // 连续的1的计数器
int result = 0; // 最终的结果计数器
// 遍历所有输入数据
for (int i = 0; i < data.size(); ++i) {
if (data[i] == 1) {
count++;
if (count == 3) {
result++;
count = 0; // 连续3个1的情况,重置计数器
}
} else {
if (count) {
result++; // 处理有连续1但未达到3的情况
}
count = 0; // 遇到0,重置计数器
}
}
// 处理结束后,如果还有未完成的连续1
if (count) {
result++;
}
// 输出结果
cout << result << endl;
return 0;
}
绘图机器、计算面积/
#include <iostream>
#include <cmath> // for std::abs
using namespace std;
typedef long long ll;
int main() {
ll N, E;
cin >> N >> E;
ll x0 = 0, y0 = 0;
ll x1, dealtay;
ll res = 0;
for (int i = 0; i < N; ++i) {
cin >> x1 >> dealtay;
res += abs(y0) * (x1 - x0); // 计算当前段的面积
y0 += dealtay; // 更新y的值
x0 = x1; // 更新x的值
}
res += abs(y0) * (E - x0); // 处理最后一个段到E的面积
cout << res << endl;
return 0;
}
求最多可以派出多少支团队x
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
std::cin >> n;
std::vector<int> capacities(n);
for (int i = 0; i < n; ++i) {
std::cin >> capacities[i];
}
int minCap;
std::cin >> minCap;
// 使用 std::sort 对 capacities 进行升序排序
std::sort(capacities.begin(), capacities.end());
int l = 0;
int r = n - 1;
int ans = 0;
// 处理单人组队
while (r >= l && capacities[r] >= minCap) {
--r;
++ans;
}
// 处理双人组队
while (l < r) {
int sum = capacities[l] + capacities[r];
if (sum >= minCap) {
++ans;
++l;
--r;
} else {
++l;
}
}
std::cout << ans << std::endl;
return 0;
}
找朋友m
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> w(n);
vector<int> res(n);
stack<int> stk;
for (int i = 0; i < n; i++) {
cin >> w[i];
}
for (int i = n - 1; i >= 0; i--) {
while (!stk.empty() && w[stk.top()] <= w[i]) {
stk.pop();
}
if (!stk.empty()) {
res[i] = stk.top();
}
stk.push(i);
}
for (int i = 0; i < n; i++) {
cout << res[i];
if (i + 1 < n) {
cout << " ";
}
}
return 0;
}
200
最长子字符串的长度(二)
#include <stdio.h>
#include <math.h>
int main() {
int m, n;
scanf("%d %d", &m, &n);
// 记录前车到达终点的时刻,本题后车不可能比前车更早到达,因此如果后车到达时刻 < 前车到达时刻arrived,则后车也是按照前车arrived时刻达到
double arrived = 0;
for(int i=0; i<m; i++) {
// 当前车的速度
double speed;
scanf("%lf", &speed);
// 当前车到达终点的时刻
// * 当前车如果比前车更早到达,则被前车阻碍,按前车到达时间算
// * 当前车如果比前车更晚到达,则不被前车阻碍,按后车到达时间算
arrived = fmax(arrived, n / speed + i); // n*1.0/speed是行驶花费时间; i是第i辆车的出发时间
}
// 到达时刻 - 出发时刻 = 路上花费的时间
double cost = arrived - (m - 1);
// 至多保留3个小数位
char res[100];
sprintf(res, "%.3f", cost);
// %g 格式 不会打印无效小数位
printf("%g", atof(res));
return 0;
}
智能驾驶
#include <climits>
#include <cstdio>
#include <deque>
#include <iostream>
#include <vector>
using namespace std;
int m, n;
vector<vector<int>> matrix;
struct node{
int x;
int y;
int init;
int remain;
bool flag;
};
int offset[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int bfs(){
deque<node> q;
node start{0, 0};
if(matrix[0][0] == -1){
start.init = 0;
start.remain = 100;
start.flag = true;
}
else{
start.init = matrix[0][0];
start.remain = 0;
start.flag = false;
}
q.push_back((start));
vector<vector<int>> dis_init(m, vector<int>(n, INT_MAX));
vector<vector<int>> dis_remain(m, vector<int>(n, 0));
while (!q.empty()) {
node temp = q.front();
q.pop_front();
for(int i = 0; i < 4; ++i){
int newx = temp.x + offset[i][0];
int newy = temp.y + offset[i][1];
if(newx < 0 || newx >= m || newy < 0 || newy >= n || matrix[newx][newy] == 0){
continue;
}
int init = temp.init;
int remain = temp.remain;
bool flag = temp.flag;
if(matrix[newx][newy] == -1){
remain = 100;
flag = true;
}
else{
remain -= matrix[newx][newy];
}
if(remain < 0){
if(flag){
continue;
}
else{
init -= remain;
remain = 0;
}
}
if(init > 100 || init > dis_init[newx][newy]){
continue;
}
if(init < dis_init[newx][newy] || remain > dis_remain[newx][newy]){
dis_init[newx][newy] = init;
dis_remain[newx][newy] = remain;
q.push_back(node{newx, newy, init, remain, flag});
}
}
}
if(dis_init[m - 1][n - 1] == INT_MAX){
return -1;
}
else{
return dis_init[m - 1][n - 1];
}
}
int main(){
scanf("%d,%d", &m, &n);
matrix = vector<vector<int>>(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
scanf("%d", &matrix[i][j]);
getchar();
}
}
int res = bfs();
cout << res;
}
运输时间
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <ios>
#include <iostream>
#include <vector>
using namespace std;
int main(){
int m, n;
cin >> m >> n;
vector<double> s(m);
double arrived = 0;
for(int i = 0; i < m; ++i){
cin >> s[i];
arrived = max(arrived, n / s[i] + i);
}
double res = arrived - (m - 1);
char ans[100];
sprintf(ans, "%.3f", res);
printf("%g", atof(ans));
}
爱吃蟠桃的孙悟空/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// 计算分组的数量
int check(const vector<int>& m, int mid) {
int res = 0;
for (int num : m) {
res += (num + mid - 1) / mid; // 计算所需的组数
}
return res;
}
int main() {
string str;
getline(cin, str); // 读取整行输入
stringstream ss(str);
vector<int> nums;
int num;
while (ss >> num) {
nums.push_back(num);
if (ss.peek() == ',') ss.ignore(); // 忽略逗号
}
int x;
cin >> x;
int n = nums.size();
if (n > x) {
cout << 0 << endl; // 如果数字个数大于 x,返回 0
return 0;
}
// 线性扫描方法来寻找最小的 mid 值
int mid = 1; // 从1开始
while (true) {
if (check(nums, mid) <= x) {
cout << mid << endl; // 找到满足条件的最小 mid
break;
}
mid++; // 增加 mid
}
return 0;
}
石头剪刀布游戏m
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main(){
string id, shape;
map<string, vector<string>> mp;
bool a = false;
bool b = false;
bool c = false;
while(cin >> id >> shape){
mp[shape].push_back(id);
if(shape == "A"){
a = true;
}
else if(shape == "B"){
b = true;
}
else{
c = true;
}
}
if(((a && b) || (a && c) || (b && c)) && !(a && b && c)){
if(a && b){
vector<string> res = mp["A"];
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); ++i){
cout << res[i] << endl;
}
}
else if(a && c){
vector<string> res = mp["C"];
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); ++i){
cout << res[i] << endl;
}
}
else if(b && c){
vector<string> res = mp["B"];
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); ++i){
cout << res[i] << endl;
}
}
}
else{
cout << "NULL";
}
}
电脑病毒感染m
#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<vector<int>> grid(n + 1, vector<int>(n + 1));
map<int, vector<int>> mp;
for (int i = 0; i < k; ++i) {
int a, b, c;
cin >> a >> b >> c;
mp[a].push_back(b);
grid[a][b] = c;
}
int start;
cin >> start;
vector<int> queue;
vector<int> mintime(n + 1, INT_MAX);
mintime[start] = 0;
queue.push_back(start);
while (!queue.empty()) {
vector<int> newqueue;
for (int i = 0; i < queue.size(); ++i) {
int x = queue[i];
vector<int> node = mp[x];
for (int j = 0; j < node.size(); ++j) {
int y = node[j];
if (grid[x][y] > 0 && mintime[x] + grid[x][y] < mintime[y]) {
newqueue.push_back(y);
mintime[y] = mintime[x] + grid[x][y];
}
}
}
queue = newqueue;
}
sort(mintime.begin(), mintime.end());
if (mintime[n - 1] == INT_MAX) {
cout << -1;
}
else {
cout << mintime[n - 1];
}
}
小朋友分组最少调整次数
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 90000
typedef struct ListNode {
int num;
int count;
struct ListNode* next;
} ListNode;
typedef struct LinkedList {
int size;
ListNode* head;
ListNode* tail;
} LinkedList;
LinkedList* new_LinkedList() {
LinkedList* link = (LinkedList*) malloc(sizeof(LinkedList));
link->size = 0;
link->head = NULL;
link->tail = NULL;
return link;
}
void addFirst_LinkedList(LinkedList* link, int num, int count) {
ListNode* node = (ListNode*) malloc(sizeof(ListNode));
node->num = num;
node->count = count;
node->next = NULL;
if(link->size == 0) {
link->head = node;
link->tail = node;
} else {
node->next = link->head;
link->head = node;
}
link->size++;
}
void addLast_LinkedList(LinkedList* link, int num, int count) {
ListNode* node = (ListNode*) malloc(sizeof(ListNode));
node->num = num;
node->count = count;
node->next = NULL;
if(link->size == 0) {
link->head = node;
link->tail = node;
} else {
link->tail->next = node;
link->tail = node;
}
link->size++;
}
ListNode* removeFirst_LinkedList(LinkedList* link) {
if(link->size == 0) exit(-1);
ListNode* removed = link->head;
if(link->size == 1) {
link->head = NULL;
link->tail = NULL;
} else {
link->head = link->head->next;
}
link->size--;
return removed;
}
LinkedList* confirm(LinkedList* queue, int confirmed_num) {
// 此方法用于剔除掉队列中已被调整完位置的小朋友,并且抽离后,尝试合并抽离位置前后的小朋友(如果是同一组)
// 时间复杂度有点高这里,可能会超时
LinkedList* back_queue = new_LinkedList();
while (queue->size > 0) {
ListNode* first = removeFirst_LinkedList(queue);
if(first->num == confirmed_num) {
continue;
}
if(back_queue->size == 0 || back_queue->tail->num != first->num) {
addLast_LinkedList(back_queue, first->num, first->count);
} else {
back_queue->tail->count += first->count;
}
}
return back_queue;
}
int main() {
// 初始小朋友(序号)排队顺序
int nums[MAX_SIZE];
int nums_size = 0;
while (scanf("%d", &nums[nums_size++])) {
if (getchar() != ' ') break;
}
// 序号->组号 映射关系
int map[nums_size + 1];
for (int i = 0; i < nums_size; i++) {
int num;
scanf("%d", &num);
map[num] = i / 3;
}
// 相邻相同组号合并统计
LinkedList* queue = new_LinkedList();
for (int i = 0; i < nums_size; i++) {
int num = map[nums[i]];
if(queue->size == 0 || queue->tail->num != num) {
addLast_LinkedList(queue, num, 1);
} else {
queue->tail->count++;
}
}
// 记录调整次数
int moved_count = 0;
while(queue->size > 0) {
ListNode* first = removeFirst_LinkedList(queue);
// 当first.count = 1 时,情况如下
// 1 x 1 1 y z
// 1 x 1 y 1 z
if(first->count == 1) {
ListNode* x = queue->head;
// 判断x是否存在连续完整分组
while (x->count == 3) {
removeFirst_LinkedList(queue);
x = queue->head;
}
if(x->num == first->num && x->count == 2) {
// 情况:1 2 2 2 x[1 1]
// 将开头1,移动进x中
moved_count += 1;
removeFirst_LinkedList(queue);
} else {
// 情况如下:
// 1 x[2 2] 1 1
// 1 x[2] 1 2 1
// 将后面的两个1移动到开头
moved_count += 2;
queue = confirm(queue, first->num);
}
} else if(first->count == 2) {
// 当first.count == 2 时,情况如下:
// 1 1 x 1 y z
moved_count += 1;
queue = confirm(queue, first->num);
}
}
printf("%d\n", moved_count);
return 0;
}
二叉树计算m
思路:
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;
struct treenode {
int val;
int childsum;
treenode* left;
treenode* right;
};
bool notequal(vector<int> a, vector<int> b) {
if (a.size() != b.size()) {
return true;
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (a != b) {
return true;
}
return false;
}
treenode* buildtree(vector<int> pre, vector<int> mid) {
if (pre.empty()) {
return nullptr;
}
treenode* root = new treenode;
root->val = pre[0];
for (int i = 0; i < mid.size(); ++i) {
if (mid[i] == pre[0]) {
vector<int> leftmid(mid.begin(), mid.begin() + i);
vector<int> rightmid(mid.begin() + i + 1, mid.end());
vector<int> leftpre(pre.begin() + 1, pre.begin() + i + 1);
vector<int> rightpre(pre.end() - (mid.size() - i - 1), pre.end());
if (notequal(leftmid, leftpre) || notequal(rightmid, rightpre)) {
continue;
}
root->left = buildtree(leftpre, leftmid);
root->right = buildtree(rightpre, rightmid);
int rightchildsum = (root->right == nullptr) ? 0 : (root->right->val + root->right->childsum);
int leftchildsum = (root->left == nullptr) ? 0 : (root->left->val + root->left->childsum);
root->childsum = rightchildsum + leftchildsum;
break;
}
}
return root;
}
void midorder(treenode* root) {
if (root == nullptr) {
return;
}
treenode* left = root->left;
if (left != nullptr) {
midorder(left);
}
cout << root->childsum << " ";
treenode* right = root->right;
if (right != nullptr) {
midorder(right);
}
}
int main() {
int n;
vector<int> vec;
vector<int> mid;
vector<int> pre;
while (cin >> n) {
vec.push_back(n);
}
int size = vec.size() / 2;
for (int i = 0; i < size; ++i) {
mid.push_back(vec[i]);
}
for (int i = size; i < vec.size(); ++i) {
pre.push_back(vec[i]);
}
treenode* root = buildtree(pre, mid);
midorder(root);
}
分月饼 90 %
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 递归函数来计算符合条件的分配方式
void countWays(int m, int n, int minPies, vector<int>& distribution, int& count) {
if (m == 0) {
// 当所有员工都分配完毕
if (n == 0) {
// 检查分配是否符合约束条件
vector<int> sorted_distribution = distribution;
sort(sorted_distribution.begin(), sorted_distribution.end(), greater<int>());
// 检查最大值和次大值的差是否小于等于3
for (int i = 0; i < sorted_distribution.size() - 1; ++i) {
if (sorted_distribution[i] - sorted_distribution[i + 1] > 3) return;
}
count++;
}
return;
}
// 递归地分配月饼给当前员工
for (int i = minPies; i <= n; ++i) {
// 确保不会重复计数相同的分配
if (distribution.empty() || i >= distribution.back()) {
distribution.push_back(i);
countWays(m - 1, n - i, i, distribution, count);
distribution.pop_back();
}
}
}
int main() {
int m, n;
cin >> m >> n;
vector<int> distribution;
int count = 0;
int minPies = 1; // 每个员工至少1个月饼
countWays(m, n, minPies, distribution, count);
cout << count << endl;
return 0;
}
连续出牌数量、最长连续手牌v
#include <iostream>
#include <vector>
#include <string>
#include <bits/stdc++.h>
using namespace std;
struct Card {
char color;
int number;
};
// Global variables
vector<Card> cards;
vector<bool> used;
int maxCards = 0;
int n;
// Helper function to count the maximum number of cards that can be played starting from the current card
void backtrack(int currentCount, char lastColor, int lastNumber) {
maxCards = max(maxCards, currentCount); // Update the maximum number of cards played
for (int i = 0; i < n; i++) {
if (used[i]) continue; // Skip if the card is already used
if (cards[i].color == lastColor || cards[i].number == lastNumber) {
// Mark the current card as used
used[i] = true;
// Recursively try to play the next card
backtrack(currentCount + 1, cards[i].color, cards[i].number);
// Unmark the card to try other possibilities
used[i] = false;
}
}
}
int main() {
string numbersStr, colorsStr;
// Read the numbers of the cards
getline(cin, numbersStr);
istringstream numStream(numbersStr);
int number;
vector<int> numbers;
while (numStream >> number) {
numbers.push_back(number);
}
// Read the colors of the cards
getline(cin, colorsStr);
istringstream colorStream(colorsStr);
char color;
vector<char> colors;
while (colorStream >> color) {
colors.push_back(color);
}
n = numbers.size();
cards.resize(n);
used.resize(n, false);
// Initialize the cards vector
for (int i = 0; i < n; i++) {
cards[i].color = colors[i];
cards[i].number = numbers[i];
}
// Try starting with each card
for (int i = 0; i < n; i++) {
used[i] = true;
backtrack(1, cards[i].color, cards[i].number);
used[i] = false;
}
cout << maxCards << endl; // Output the maximum number of cards that can be played
return 0;
}
5G网络建设m
#include <algorithm>
#include <climits>
#include <cmath>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int n, m;
int mincost;
int prim(vector<vector<int>> paths) {
vector<int> dis(n + 1, INT_MAX);
vector<bool> used(n + 1, false);
used[1] = true;
int count = 1;
for (int i = 1; i <= n; ++i) {
dis[i] = paths[1][i];
}
while (count < n) {
int mindis = INT_MAX;
int minid = 0;
for (int i = 1; i <= n; ++i) {
if (dis[i] < mindis && !used[i]) {
mindis = dis[i];
minid = i;
}
}
if (minid == 0) {
return -1;
}
used[minid] = true;
count++;
mincost += dis[minid];
for (int i = 1; i <= n; ++i) {
if (!used[i] && paths[i][minid] < dis[i]) {
dis[i] = paths[i][minid];
}
}
}
return mincost;
}
int main() {
cin >> n >> m;
vector<vector<int>> paths(n + 1, vector<int>(n + 1));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
paths[i][j] = INT_MAX;
}
}
for (int i = 0; i < m; ++i) {
int x, y, z, p;
cin >> x >> y >> z >> p;
if (p == 0) {
paths[x][y] = z;
paths[y][x] = z;
}
else {
paths[x][y] = 0;
paths[y][x] = 0;
}
}
cout << prim(paths);
}
攀登者2m
#include <algorithm>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(){
string s;
cin >> s;
stringstream ss(s);
string num;
vector<int> nums;
while(getline(ss, num, ',')){
nums.push_back(stoi(num));
}
int n = nums.size();
int strength;
cin >> strength;
set<int> res;
int index = 0;
while(index < n && nums[index] != 0){
index++;
}
int cost = 0;
for(int i = index + 1; i < n; ++i){
if(nums[i] == 0){
cost = 0;
continue;
}
int k = nums[i] - nums[i - 1];
if(k > 0){
cost += 3 * k;
if(i + 1 == n || nums[i + 1] < nums[i]){
if(cost < strength){
res.insert(i);
}
}
}
else{
cost -= 3 * k;
}
}
reverse(nums.begin(), nums.end());
index = 0;
while(index < n && nums[index] != 0){
index++;
}
cost = 0;
for(int i = index + 1; i < n; ++i){
if(nums[i] == 0){
cost = 0;
continue;
}
int k = nums[i] - nums[i - 1];
if(k > 0){
cost += 3 * k;
if(i + 1 == n || nums[i + 1] < nums[i]){
if(cost < strength){
res.insert(n - i - 1);
}
}
}
else{
cost -= 3 * k;
}
}
cout << res.size();
}
园区参观路径 88%
#include <iostream>
#include <vector>
using namespace std;
// 用于检查当前位置是否有效
bool isValid(int x, int y, int n, int m, const vector<vector<int>>& matrix, vector<vector<bool>>& visited) {
return (x >= 0 && x < n && y >= 0 && y < m && matrix[x][y] == 0 && !visited[x][y]);
}
// 回溯函数
int countPaths(int x, int y, int n, int m, const vector<vector<int>>& matrix, vector<vector<bool>>& visited) {
// 如果到达终点
if (x == n - 1 && y == m - 1) {
return 1;
}
visited[x][y] = true; // 标记当前位置为已访问
int totalPaths = 0;
// 尝试向下移动
if (isValid(x + 1, y, n, m, matrix, visited)) {
totalPaths += countPaths(x + 1, y, n, m, matrix, visited);
}
// 尝试向右移动
if (isValid(x, y + 1, n, m, matrix, visited)) {
totalPaths += countPaths(x, y + 1, n, m, matrix, visited);
}
visited[x][y] = false; // 回溯,取消当前位置的标记
return totalPaths;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> matrix(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
// 如果起点或终点是障碍物,直接输出 0
if (matrix[0][0] == 1 || matrix[n - 1][m - 1] == 1) {
cout << "0" << endl;
return 0;
}
// 用于标记已访问的位置
vector<vector<bool>> visited(n, vector<bool>(m, false));
// 从起点 (0, 0) 开始回溯
int result = countPaths(0, 0, n, m, matrix, visited);
cout << result << endl;
return 0;
}
部门人力分配m
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int m;
vector<long> requirements;
bool check(long x){
int l = 0;
int r = requirements.size() - 1;
int time = 0;
while(l <= r){
if(requirements[l] + requirements[r] <= x){
l++;
}
r--;
time++;
}
return m >= time;
}
int main(){
cin >> m;
long require;
while(cin >> require){
requirements.push_back(require);
}
sort(requirements.begin(), requirements.end());
int n = requirements.size();
long minres = requirements[n - 1];
long maxres = requirements[n - 1] + requirements[n - 2];
long res = maxres;
while(minres <= maxres){
long mid = (minres + maxres) / 2;
if(check(mid)){
res = mid;
maxres = mid - 1;
}
else{
minres = mid + 1;
}
}
cout << res;
}
结队编程m
#include <csignal>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int n;
vector<int> level;
long res = 0;
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
level.push_back(num);
}
for(int i = 1; i < n - 1; ++i){
int x = level[i];
long leftsmallcount = 0;
long leftbigcount = 0;
for(int j = 0; j < i; ++j){
if(level[j] < x){
leftsmallcount++;
}
else{
leftbigcount++;
}
}
long rightsmallcount = 0;
long rightbigcount = 0;
for(int k = i + 1; k < n; ++k){
if(level[k] < x){
rightsmallcount++;
}
else{
rightbigcount++;
}
}
res += leftsmallcount * rightbigcount + leftbigcount * rightsmallcount;
}
cout << res;
}
数据单元的变化替换
#include <cerrno>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
regex pattern("<.*?>");
vector<string> excel;
bool change(int index) {
smatch matches;
while (regex_search(excel[index], matches, pattern)) {
string reference = matches[0];
if (reference.size() != 3) {
return false;
}
char ch = reference[1];
int reference_index = ch - 'A';
if (ch < 'A' || ch > 'Z' || reference_index == index || reference_index >= excel.size()) {
return false;
}
if (!change(reference_index)) {
return false;
}
excel[index] = regex_replace(excel[index], pattern, excel[reference_index], regex_constants::format_first_only);
}
return true;
}
int main() {
string s;
cin >> s;
stringstream ss(s);
string str;
while (getline(ss, str, ',')) {
excel.push_back(str);
}
if(excel.size() > 26){
cout << -1;
return 0;
}
for (int i = 0; i < excel.size(); ++i) {
if (excel[i].length() > 100) {
cout << -1;
return 0;
}
if (!change(i)) {
cout << -1;
return 0;
}
if (excel[i].length() > 100) {
cout << -1;
return 0;
}
for (int j = 0; j < excel[i].size(); ++j) {
char ch = excel[i][j];
if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'))) {
cout << -1;
return 0;
}
}
}
cout << excel[0];
for (int i = 1; i < excel.size(); ++i) {
cout << ',' << excel[i];
}
}
高效货运
枚举
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int wa, wb, wt, pa, pb;
cin >> wa >> wb >> wt >> pa >> pb;
int res = 0;
int maxa = (wt % wa == 0) ? wt / wa - 1 : wt / wa;
int maxb = (wt % wb == 0) ? wt / wb - 1 : wt / wb;
if (maxa > maxb) {
int k = maxb;
for (int i = k; i > 0; --i) {
int remain = wt - i * wb;
if (remain % wa == 0) {
int j = remain / wa;
res = max(res, pa * j + pb * i);
}
}
}
else {
int k = maxa;
for (int i = k; i > 0; --i) {
int remain = wt - i * wa;
if (remain % wb == 0) {
int j = remain / wb;
res = max(res, pa * i + pb * j);
}
}
}
cout << res;
}
找数字m
#include <algorithm>
#include <cmath>
#include <functional>
#include <iostream>
#include <mutex>
#include <vector>
using namespace std;
int main(){
long m;
cin >> m;
vector<int> vec;
while(m != 0){
vec.push_back(m % 2);
m = m / 2;
}
int n = vec.size();
vec.push_back(0);
for(int i = 0; i < n; ++i){
if(vec[i] && !vec[i + 1]){
vec[i] = 0;
vec[i + 1] = 1;
sort(vec.begin(), vec.begin() + i, greater<int>());
break;
}
}
long res = 0;
for(int i = 0; i < vec.size(); ++i){
res += vec[i] * pow(2, i);
}
cout << res;
}
中文分词模拟器 not
#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
#include <algorithm>
using namespace std;
// Function to perform greedy segmentation
vector<string> greedySegmentation(const string& s, const unordered_set<string>& dictionary) {
vector<string> result;
int n = s.size();
int i = 0;
while (i < n) {
int maxLength = 0;
string bestMatch;
// Try to find the longest valid word starting from position i
for (int j = i + 1; j <= n; ++j) {
string word = s.substr(i, j - i);
if (dictionary.count(word) && word.length() > maxLength) {
maxLength = word.length();
bestMatch = word;
}
}
if (maxLength == 0) {
// No valid segmentation found, move to the next character
result.push_back(string(1, s[i]));
i++;
} else {
result.push_back(bestMatch);
i += maxLength;
}
}
return result;
}
int main() {
string s;
getline(cin, s);
string wordsInput;
getline(cin, wordsInput);
unordered_set<string> dictionary;
size_t start = 0;
size_t end = wordsInput.find(",");
while (end != string::npos) {
dictionary.insert(wordsInput.substr(start, end - start));
start = end + 1;
end = wordsInput.find(",", start);
}
dictionary.insert(wordsInput.substr(start, end));
vector<string> result = greedySegmentation(s, dictionary);
// Output result
for (size_t i = 0; i < result.size(); ++i) {
if (i > 0) cout << ",";
cout << result[i];
}
cout << endl;
return 0;
}
符号运算
#include <cmath>
#include <cstdio>
#include <iostream>
#include <map>
#include <stack>
#include <string>
using namespace std;
struct fraction {
int father;
int child;
};
stack<char> opsign;
stack<fraction> opnum;
map<char, int> priority = { {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} };
void calculate() {
fraction op2 = opnum.top();
opnum.pop();
fraction op1 = opnum.top();
opnum.pop();
char op = opsign.top();
opsign.pop();
fraction res;
switch (op) {
case '+':
res.father = op1.father * op2.father;
res.child = op1.child * op2.father + op2.child * op1.father;
break;
case '-':
res.father = op1.father * op2.father;
res.child = op1.child * op2.father - op2.child * op1.father;
break;
case '*':
res.father = op1.father * op2.father;
res.child = op1.child * op2.child;
break;
case '/':
res.father = op1.father * op2.child;
res.child = op1.child * op2.father;
break;
}
opnum.push(res);
}
int gcd(int a, int b) {
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
int main() {
string s;
getline(cin, s);
string numstr = "";
for (int i = 0; i < s.length(); ++i) {
if (s[i] >= '0' && s[i] <= '9') {
while (s[i] >= '0' && s[i] <= '9' && i < s.length()) {
numstr += s[i];
i++;
}
fraction num;
num.father = 1;
num.child = stoi(numstr);
opnum.push(num);
numstr.clear();
}
if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
char sign = s[i];
while (!opsign.empty() && opsign.top() != '(' && priority[sign] <= priority[opsign.top()]) {
calculate();
}
opsign.push(sign);
}
else if (s[i] == '(') {
opsign.push(s[i]);
}
else if (s[i] == ')') {
while (opsign.top() != '(') {
calculate();
}
opsign.pop();
}
}
while (opnum.size() > 1) {
calculate();
}
fraction res = opnum.top();
if (res.father == 0) {
cout << "ERROR";
return 0;
}
int k = gcd(res.father, res.child);
int father = res.father / k;
int child = res.child / k;
bool sign = (father > 0 && child > 0) || (father < 0 && child < 0);
if (!sign) {
cout << '-';
}
if (abs(father) == 1) {
cout << abs(child);
}
else {
cout << abs(child) << '/' << abs(father);
}
}
根据IP查找城市
#include <algorithm>
#include <array>
#include <climits>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string &s, char ch){
stringstream ss(s);
string token;
vector<string> res;
while(getline(ss, token, ch)){
res.push_back(token);
}
return res;
}
struct city{
string name;
int startip;
int endip;
};
int ip2dec(string ip){
int res = 0;
stringstream ss(ip);
string token;
while (getline(ss, token, '.')) {
res = stoi(token) | res << 8;
}
return res;
}
int main(){
string s1;
cin >> s1;
vector<string> cities = split(s1, ';');
string s2;
cin >> s2;
vector<string> queryips = split(s2, ',');
vector<city> vec;
for(int i = 0; i < cities.size(); ++i){
vector<string> temp = split(cities[i], '=');
string cityname = temp[0];
vector<string> ips = split(temp[1], ',');
int startip = ip2dec(ips[0]);
int endip = ip2dec(ips[1]);
city currentcity{cityname, startip, endip};
vec.push_back(currentcity);
}
int n = queryips.size();
vector<string> res(n);
for(int i = 0; i < n; ++i){
int ip = ip2dec(queryips[i]);
int minlen = INT_MAX;
string cityname = "";
for(int j = 0; j < vec.size(); ++j){
if(ip >= vec[j].startip && ip <= vec[j].endip){
if(vec[j].endip - vec[j].startip + 1 < minlen){
cityname = vec[j].name;
minlen = vec[j].endip - vec[j].startip + 1;
}
else if(vec[j].endip - vec[j].startip + 1 == minlen){
cityname = max(res[i], vec[j].name);
}
}
}
res[i] = cityname;
}
cout << res[0];
for(int i = 1; i < res.size(); ++i){
cout << ',' << res[i];
}
}
文件缓存系统m
#include <algorithm>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
struct file {
int size;
int count;
int time;
};
bool cmp(pair<string, file> a, pair<string, file> b) {
file fa = a.second;
file fb = b.second;
if (fa.count == fb.count) {
return fa.time < fb.time;
}
else {
return fa.count < fb.count;
}
}
int main() {
int m, n;
cin >> m >> n;
vector<pair<string, file>> files;
map<string, file> mp;
int currentsize = m;
for (int i = 0; i < n; ++i) {
string op, filename;
cin >> op >> filename;
if (op == "put") {
string filesize;
cin >> filesize;
if (mp.find(filename) != mp.end()) {
continue;
}
int size = stoi(filesize);
if (currentsize < size) {
while (currentsize < size && !files.empty()) {
currentsize += files.begin()->second.size;
files.erase(files.begin());
mp.erase(filename);
}
}
if (currentsize >= size) {
file f{ size, 0, i };
files.push_back(make_pair(filename, f));
mp[filename] = f;
currentsize -= size;
sort(files.begin(), files.end(), cmp);
}
}
else if (op == "get") {
for (int j = 0; j < files.size(); ++j) {
if (files[j].first == filename) {
files[j].second.count++;
files[j].second.time = i;
sort(files.begin(), files.end(), cmp);
break;
}
}
}
}
if (files.empty()) {
cout << "NONE";
}
else {
sort(files.begin(), files.end(), [](pair<string, file> a, pair<string, file> b) {
return a.first < b.first;
});
cout << files[0].first;
for (int i = 1; i < files.size(); ++i) {
cout << ',' << files[i].first;
}
}
}
员工派遣m
#include <algorithm>
#include <iostream>
using namespace std;
int x, y, cntx, cnty;
bool check(int num){
int a = num / x;
int b = num / y;
int c = num / (x * y);
int remainx = max(0, cntx - (b - c));
int remainy = max(0, cnty - (a - c));
return remainx + remainy <= num - a - b + c;
}
int main(){
cin >> x >> y >> cntx >> cnty;
int mink = 1;
int maxk = 1e9;
while(mink <= maxk){
int mid = (mink + maxk) / 2;
if(check(mid)){
maxk = mid - 1;
}
else{
mink = mid + 1;
}
}
cout << mink;
}
跳格子3m
#include <algorithm>
#include <deque>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> scores(n);
for (int i = 0; i < n; ++i) {
cin >> scores[i];
}
int k;
cin >> k;
vector<int> dp(n);
dp[0] = scores[0];
int len = k + 1;
deque<int> q;
q.push_back(dp[0]);
for(int i = 1; i < min(len, n); ++i){
dp[i] = q.front() + scores[i];
while (!q.empty() && q.back() < dp[i]) {
q.pop_back();
}
q.push_back(dp[i]);
}
for(int i = len; i < n; ++i){
if(dp[i - len] == q.front()){
q.pop_front();
}
dp[i] = q.front() + scores[i];
while (!q.empty() && q.back() < dp[i]) {
q.pop_back();
}
q.push_back(dp[i]);
}
cout << dp[n - 1];
}
贪吃的猴子

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int len;
int n;
vector<int> nums;
int main() {
cin >> len;
for (int i = 0; i < len; ++i) {
int num;
cin >> num;
nums.push_back(num);
}
cin >> n;
int leftsum = 0;
for (int i = 0; i < n; ++i) {
leftsum += nums[i];
}
int res = leftsum;
int l = n - 1;
int r = len - 1;
int sum = leftsum;
while (l >= 0) {
sum = sum - nums[l] + nums[r];
l--;
r--;
res = max(res, sum);
}
cout << res;
}
项目排期
#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int n;
vector<int> works;
vector<int> workers;
bool check(int index, int time) {
if (index == works.size()) {
return true;
}
for (int i = 0; i < n; ++i) {
if(i > 0 && workers[i] == workers[i - 1]){
continue;
}
if (workers[i] + works[index] <= time) {
workers[i] += works[index];
if (check(index + 1, time)) {
return true;
}
workers[i] -= works[index];
}
}
return false;
}
int main() {
int num;
while (cin >> num) {
works.push_back(num);
}
n = works.back();
works.pop_back();
sort(works.begin(), works.end(), greater<int>());
int mintime = works[0];
int maxtime = accumulate(works.begin(), works.end(), 0);
int res = maxtime;
for (int i = 0; i < n; ++i) {
workers.push_back(0);
}
while (mintime <= maxtime) {
for (int i = 0; i < n; ++i) {
workers[i] = 0;
}
int mid = (mintime + maxtime) / 2;
if (check(0, mid)) {
res = mid;
maxtime = mid - 1;
}
else {
mintime = mid + 1;
}
}
cout << res;
}
亲子游戏

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 定义广度优先搜索函数
int bfs(queue<pair<int, int>>& q, vector<vector<int>>& g, vector<vector<int>>& w, vector<int>& dx, vector<int>& dy, int n) {
while (!q.empty()) {
// 从队列中取出当前位置
pair<int, int> t = q.front();
q.pop();
int x = t.first, y = t.second;
// 如果当前位置为终点,返回糖果数量
if (g[x][y] == -2) {
return w[x][y];
}
// 遍历四个方向
for (int i = 0; i < 4; i++) {
int x1 = x + dx[i], y1 = y + dy[i];
// 判断是否越界或者是不可访问的位置
if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= n || g[x1][y1] == -1) {
continue;
}
// 如果该位置未访问过,将其加入队列,并初始化糖果数量为0
if (w[x1][y1] == 0) {
q.push({x1, y1});
w[x1][y1] = 0;
}
// 更新糖果数量,取当前位置糖果数和上一步位置的糖果数量之和的最大值
w[x1][y1] = max(w[x1][y1], max(0, g[x1][y1]) + w[x][y]);
}
}
// 如果无法到达终点,返回-1
return -1;
}
int main() {
int n;
cin >> n;
// 存储糖果数量的二维数组w,初始值为0
vector<vector<int>> w(n, vector<int>(n, 0));
// 存储起点坐标的队列
queue<pair<int, int>> q;
// 存储地图元素的二维数组g
vector<vector<int>> g(n, vector<int>(n, 0));
// 读取地图元素并初始化起点和糖果数量数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> g[i][j];
if (g[i][j] == -3) { // 添加起点
q.push({i, j});
w[i][j] = 0;
}
}
}
// 四个方向的移动
vector<int> dx = {-1, 1, 0, 0};
vector<int> dy = {0, 0, 1, -1};
// 调用广度优先搜索函数获取结果
int result = bfs(q, g, w, dx, dy, n);
cout << result << endl;
return 0;
}
任务处理、可以处理的最大任务数
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
priority_queue<int, vector<int>, less<int>> queue;
vector<pair<int, int>> task(n);
for (int i = 0; i < n; ++i) {
cin >> task[i].first >> task[i].second;
}
sort(task.begin(), task.end(), [](pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
});
int res = 0;
int lastei = INT_MAX;
for(int i = 0; i < n; ++i){
int si = task[i].first;
int ei = task[i].second;
while(!queue.empty() && ei < lastei){
if(queue.top() <= lastei){
lastei--;
res++;
}
queue.pop();
}
queue.push(si);
lastei = ei;
}
while(!queue.empty()){
if(queue.top() <= lastei){
res++;
lastei--;
}
queue.pop();
}
cout << res;
}
推荐多样性

#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> split(string s, char ch){
stringstream ss(s);
string token;
vector<int> res;
while(getline(ss, token, ch)){
res.push_back(stoi(token));
}
return res;
}
int main(){
int n, k;
cin >> n >> k;
string s;
vector<vector<int>> lists;
getline(cin, s);
while(getline(cin, s)){
lists.push_back(split(s, ' '));
}
int size = k * n;
vector<int> windows(size);
int idx = 0;
int listidx = 0;
while(idx < size){
bool flag = false;
for(int i = 0; i < n; ++i){
windows[idx] = lists[listidx][0];
idx++;
lists[listidx].erase(lists[listidx].begin());
if(lists[listidx].empty() && lists.size() > 1){
lists.erase(lists.begin() + listidx);
listidx = listidx % lists.size();
flag = true;
}
}
if(!flag){
listidx = (listidx + 1) % lists.size();
}
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < k; ++j){
cout << windows[j * n + i] << " ";
}
}
}
两个字符串间的最短路径问题
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
string a, b;
cin >> a >> b;
int m = b.size();
int n = a.size();
vector<int> prerow(n + 1);
vector<int> temprow(n + 1);
for(int i = 0; i <= n; ++i){
prerow[i] = i;
}
for(int i = 1; i <= m; ++i){
temprow[0] = i;
for(int j = 1; j <= n; ++j){
if(a[j - 1] == b[i - 1]){
temprow[j] = prerow[j - 1] + 1;
}
else{
temprow[j] = min(temprow[j - 1], prerow[j]) + 1;
}
}
prerow = temprow;
}
cout << prerow[n];
}
跳马

#include <algorithm>
#include <climits>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int offsets[8][2] = { {1, 2},{1, -2},{2, 1},{2, -1},{-1, 2},{-1, -2},{-2, 1},{-2, -1} };
int m, n;
set<int> reach;
void bfs(int x, int y, int k, vector<vector<int>>& steps) {
vector<vector<int>> queue;
queue.push_back({ x, y, 0 });
set<int> vis;
vis.insert(x * n + y);
while (!queue.empty() && k > 0) {
vector<vector<int>> newqueue;
for (int i = 0; i < queue.size(); ++i) {
int x = queue[i][0];
int y = queue[i][1];
int step = queue[i][2];
for (int i = 0; i < 8; ++i) {
int newx = x + offsets[i][0];
int newy = y + offsets[i][1];
int pos = newx * n + newy;
if (newx < 0 || newx >= m || newy < 0 || newy >= n || vis.count(pos) > 0) {
continue;
}
newqueue.push_back({ newx, newy, step + 1 });
steps[newx][newy] += step + 1;
vis.insert(pos);
}
}
queue = newqueue;
k--;
}
set<int> temp;
for (auto it = vis.begin(); it != vis.end(); ++it) {
if (reach.count(*it) > 0) {
temp.insert(*it);
}
}
reach = temp;
}
int main() {
cin >> m >> n;
vector<string> matrix(m);
vector<vector<int>> steps(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
cin >> matrix[i];
for (int j = 0; j < n; ++j) {
reach.insert(i * n + j);
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] != '.') {
int k = matrix[i][j] - '0';
bfs(i, j, k, steps);
}
}
}
int minstep = INT_MAX;
if (reach.empty()) {
cout << -1;
}
else {
for (auto it = reach.begin(); it != reach.end(); ++it) {
int x = *it / n;
int y = *it % n;
minstep = min(minstep, steps[x][y]);
}
cout << minstep;
}
}
路口最短时间问题

#include <algorithm>
#include <climits>
#include <ios>
#include <iostream>
#include <queue>
#include <type_traits>
#include <vector>
using namespace std;
struct node {
int prex;
int prey;
int curx;
int cury;
int cost;
};
struct cmp {
bool operator() (node a, node b) {
return a.cost > b.cost;
}
};
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> lights(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> lights[i][j];
}
}
int timeperroad, rowstart, colstart, rowend, colend;
cin >> timeperroad >> rowstart >> colstart >> rowend >> colend;
vector<vector<vector<int>>> dis(n, vector<vector<int>>(m, vector<int>(4)));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int k = 0; k < 4; ++k) {
dis[i][j][k] = INT_MAX;
}
}
}
priority_queue<node, vector<node>, cmp> queue;
queue.push(node{ -1, -1, rowstart, colstart, 0 });
for (int k = 0; k < 4; ++k) {
dis[rowstart][colstart][k] = 0;
}
vector<vector<int>> offset = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
while (!queue.empty()) {
node street = queue.top();
queue.pop();
int prex = street.prex;
int prey = street.prey;
int curx = street.curx;
int cury = street.cury;
int cost = street.cost;
for (int k = 0; k < 4; ++k) {
int newx = curx + offset[k][0];
int newy = cury + offset[k][1];
if (newx < 0 || newx >= n || newy < 0 || newy >= m) {
continue;
}
if (newx == prex && newy == prey) {
continue;
}
int newcost = cost + timeperroad;
if (prex != -1 && prey != -1 && (curx - prex) * (newy - cury) - (newx - curx) * (cury - prey) >= 0) {
newcost += lights[curx][cury];
}
if (newcost < dis[newx][newy][k]) {
dis[newx][newy][k] = newcost;
queue.push(node{ curx, cury, newx, newy, newcost });
}
}
}
int res = INT_MAX;
for (int k = 0; k < 4; ++k) {
res = min(res, dis[rowend][colend][k]);
}
cout << res;
}
字符串拼接 not 100

#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
string s;
int n;
int res;
vector<bool> used;
void recursion(int index, char pre) {
if (index == n) {
res++;
}
for (int i = 0; i < s.length(); ++i) {
if (i > 0 && s[i] == s[i - 1] && !used[i - 1]) {
continue;
}
if (used[i]) {
continue;
}
if (s[i] == pre) {
continue;
}
used[i] = true;
recursion(index + 1, s[i]);
used[i] = false;
}
}
int main() {
cin >> s >> n;
if(s.length() < n){
cout << 0;
return 0;
}
for(int i = 0; i < s.length(); ++i){
if(s[i] < 'a' || s[i] > 'z'){
cout << 0;
return 0;
}
}
sort(s.begin(), s.end());
for (int i = 0; i < s.length(); ++i) {
used.push_back(false);
}
recursion(0, '\0');
cout << res;
}
Wonderland

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> costs(4);
for(int i = 0; i < 4; ++i){
cin >> costs[i];
}
vector<int> days;
int n;
while(cin >> n){
days.push_back(n);
}
int maxday = days.back();
int index = 0;
vector<int> dp(maxday + 1);
for(int i = 1; i <= maxday; ++i){
if(i == days[index]){
int day1 = dp[i - 1] + costs[0];
int day3 = (i >= 3 ? dp[i - 3] : 0) + costs[1];
int day7 = (i >= 7 ? dp[i - 7] : 0) + costs[2];
int day30 = (i >= 30 ? dp[i - 30] : 0) + costs[3];
dp[i] = min(min(day1, day3), min(day7, day30));
index++;
}
else{
dp[i] = dp[i - 1];
}
}
cout << dp[maxday];
}
伐木工

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
struct split {
int i;
int j;
int len;
};
vector<int> res;
void recursion(split x, vector<split> splits){
if(x.i == 0){
res.push_back(x.j);
return;
}
if(x.j == 0){
res.push_back(x.i);
return;
}
recursion(splits[x.i], splits);
recursion(splits[x.j], splits);
}
int main() {
int n;
cin >> n;
vector<int> dp(n + 1);
vector<split> splits(n + 1);
dp[1] = 1;
splits[1] = { 0, 1, 1 };
for (int i = 2; i <= n; ++i) {
for (int j = 0; j <= i / 2; ++j) {
if (j == 0) {
dp[i] = i;
splits[i] = { j, i - j, 1 };
}
else {
if (j * dp[i - j] > dp[i]) {
dp[i] = j * dp[i - j];
splits[i] = { j, i - j, splits[j].len + splits[i - j].len };
}
else if (j * dp[i - j] == dp[i]) {
if (splits[i].len > splits[j].len + splits[i - j].len) {
splits[i] = { j, i - j, splits[j].len + splits[i - j].len };
}
}
}
}
}
recursion(splits[n], splits);
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); ++i){
cout << res[i] << " ";
}
}
抢7游戏(dp)
#include <iostream>
#include <vector>
using namespace std;
int main(){
int m;
cin >> m;
vector<long> dpa(m + 2);
vector<long> dpb(m + 2);
dpa[m] = 1;
for(int i = m - 1; i >= 7; --i){
dpb[i] = dpa[i + 1] + dpa[i + 2];
dpa[i] = dpb[i + 1] + dpb[i + 2];
}
cout << dpb[7];
}
寻找最优的路测线路
#include <algorithm>
#include <ios>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
int main() {
int r, c;
cin >> r >> c;
vector<vector<int>> internet(r, vector<int>(c));
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
cin >> internet[i][j];
}
}
vector<int> dis(r * c);
vector<vector<int>> offset = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} };
auto cmp = [&dis](int a, int b){
return dis[a] < dis[b];
};
priority_queue<int, vector<int>, decltype(cmp)> q(cmp);
dis[0] = internet[0][0];
q.push(0);
while (!q.empty()) {
int u = q.top();
q.pop();
int x = u / c;
int y = u % c;
for (int k = 0; k < 4; ++k) {
int newx = x + offset[k][0];
int newy = y + offset[k][1];
if (newx < 0 || newx >= r || newy < 0 || newy >= c) {
continue;
}
int v = newx * c + newy;
int newdis = min(dis[u], internet[newx][newy]);
if(newdis > dis[v]){
dis[v] = newdis;
q.push(newx * c + newy);
}
}
}
cout << dis[r * c - 1];
}
篮球游戏
#include <deque>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> split(string s, char ch){
stringstream ss(s);
string token;
vector<int> res;
while(getline(ss, token, ch)){
res.push_back(stoi(token));
}
return res;
}
int main(){
string s1;
cin >> s1;
vector<int> inputs = split(s1, ',');
string s2;
cin >> s2;
vector<int> outputs = split(s2, ',');
deque<int> q;
int index = 0;
string res = "";
for(int i = 0; i < inputs.size(); ++i){
q.push_back(inputs[i]);
while (!q.empty() && index <outputs.size()) {
int left = q.front();
int right = q.back();
if(outputs[index] == left){
res += 'L';
q.pop_front();
index++;
}
else if(outputs[index] == right){
res += 'R';
q.pop_back();
index++;
}
else{
break;
}
}
}
if(index == outputs.size()){
cout << res;
}
else{
cout << "NO";
}
}
矩阵匹配v

#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int INF = INT_MAX;
int n, m, K; // Dimensions and K value
vector<vector<int>> myMap; // Input matrix
// Helper function for BFS in the flow network
bool bfs(const vector<vector<int>>& capacity, const vector<vector<int>>& adj, vector<int>& parent) {
fill(parent.begin(), parent.end(), -1);
queue<int> q;
q.push(0); // Start from source node
parent[0] = -2;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (parent[v] == -1 && capacity[u][v] > 0) {
parent[v] = u;
if (v == n + m + 1) return true; // Found the sink
q.push(v);
}
}
}
return false;
}
// Edmonds-Karp Algorithm for Max-Flow
int edmondsKarp(vector<vector<int>>& capacity, const vector<vector<int>>& adj) {
vector<int> parent(n + m + 2);
int maxFlow = 0;
while (bfs(capacity, adj, parent)) {
int flow = INF;
int s = n + m + 1;
for (int v = s; v != 0; v = parent[v]) {
int u = parent[v];
flow = min(flow, capacity[u][v]);
}
for (int v = s; v != 0; v = parent[v]) {
int u = parent[v];
capacity[u][v] -= flow;
capacity[v][u] += flow;
}
maxFlow += flow;
}
return maxFlow;
}
// Check function to see if we can achieve the required number of matches
bool check(int p) {
vector<vector<int>> capacity(n + m + 2, vector<int>(n + m + 2, 0));
vector<vector<int>> adj(n + m + 2);
// Build the graph
for (int i = 0; i < n; ++i) {
adj[0].push_back(i + 1);
adj[i + 1].push_back(0);
capacity[0][i + 1] = 1; // Source to rows
for (int j = 0; j < m; ++j) {
if (myMap[i][j] <= p) {
adj[i + 1].push_back(n + j + 1);
adj[n + j + 1].push_back(i + 1);
capacity[i + 1][n + j + 1] = 1; // Rows to columns
}
}
}
for (int j = 0; j < m; ++j) {
adj[n + j + 1].push_back(n + m + 1);
adj[n + m + 1].push_back(n + j + 1);
capacity[n + j + 1][n + m + 1] = 1; // Columns to sink
}
int maxFlow = edmondsKarp(capacity, adj);
return maxFlow >= n - K + 1;
}
// Solve function using binary search
int solve(int mx) {
int l = 1, r = mx;
int ans = mx;
while (l <= r) {
int mid = (l + r) / 2;
if (check(mid)) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
int main() {
cin >> n >> m >> K;
myMap.resize(n, vector<int>(m));
int mx = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> myMap[i][j];
mx = max(mx, myMap[i][j]);
}
}
cout << solve(mx) << endl;
return 0;
}
最小矩阵宽度
#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
vector<vector<int>> matrix(n, vector<int>(m));
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
cin >> matrix[i][j];
}
}
int k;
cin >> k;
map<int, int> nums;
for(int i = 0; i < k; ++i){
int num;
cin >> num;
nums[num]++;
}
int l = 0;
int r = 0;
int count = k;
int minlen = INT_MAX;
while(r < m){
for(int i = 0; i < n; ++i){
int num = matrix[i][r];
if (nums.find(num) != nums.end()) {
if(nums[num] > 0){
nums[num]--;
count--;
}
else{
nums[num]--;
}
}
}
while (count == 0) {
minlen = min(minlen, r - l + 1);
for(int i = 0; i < n; ++i){
int num = matrix[i][l];
if (nums.find(num) != nums.end()) {
if(nums[num] >= 0){
nums[num]++;
count++;
}
else{
nums[num]++;
}
}
}
l++;
}
r++;
}
if(minlen == INT_MAX){
cout << -1;
}
else{
cout << minlen;
}
}
启动多任务排序

#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
map<string, int> indegree;
map<string, vector<string>> child;
string s;
while (cin >> s) {
int pos = s.find("->");
string a = s.substr(0, pos);
string b = s.substr(pos + 2);
if (indegree.find(a) == indegree.end()) {
indegree[a] = 0;
}
if (indegree.find(b) == indegree.end()) {
indegree[b] = 0;
}
indegree[a]++;
if (child.find(a) == child.end()) {
child[a] = vector<string>{};
}
if (child.find(b) == child.end()) {
child[b] = vector<string>{};
}
child[b].push_back(a);
}
deque<string> q;
for (auto it = indegree.begin(); it != indegree.end(); it++) {
if (it->second == 0) {
q.push_back(it->first);
}
}
while (!q.empty()) {
sort(q.begin(), q.end());
deque<string> newq;
for (auto it1 = q.begin(); it1 != q.end(); ++it1) {
string name1 = *it1;
cout << name1 << " ";
for (auto it2 = child[name1].begin(); it2 != child[name1].end(); ++it2) {
string name2 = *it2;
indegree[name2]--;
if (indegree[name2] == 0) {
newq.push_back(name2);
}
}
}
q = newq;
}
}
贪心歌手

#include <functional>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct city {
int m;
int d;
};
int main() {
int t, n;
cin >> t >> n;
for (int i = 0; i <= n; ++i) {
int num;
cin >> num;
t = t - num;
}
vector<city> cities(n);
for (int i = 0; i < n; ++i) {
int m, d;
cin >> m >> d;
cities[i] = { m, d };
}
priority_queue<int, vector<int>, greater<int>> q;
for (int i = 0; i < n; ++i) {
int m = cities[i].m;
int d = cities[i].d;
while (m > 0 && q.size() < t) {
q.push(m);
m = m - d;
}
if (m <= 0) {
continue;
}
while (m > q.top()) {
q.pop();
q.push(m);
m = m - d;
}
}
int res = 0;
while (!q.empty()) {
res += q.top();
q.pop();
}
cout << res << endl;
}
反射计数

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int w, h, x, y, sx, sy, t;
cin >> w >> h >> x >> y >> sx >> sy >> t;
vector<vector<int>> matrix(h, vector<int>(w));
for (int i = 0; i < h; ++i) {
string s;
cin >> s;
for (int j = 0; j < w; ++j) {
matrix[i][j] = int(s[j] - '0');
}
}
int count = 0;
if (matrix[y][x] == 1) {
count++;
}
for (int i = 0; i < t; ++i) {
y = y + sy;
x = x + sx;
if (y < 0) {
y = -y;
sy = -sy;
}
if (x < 0) {
x = -x;
sx = -sx;
}
if (y >= h) {
y = y - 2 * sy;
sy = -sy;
}
if (x >= w) {
x = x - 2 * sx;
sx = -sx;
}
if (matrix[y][x] == 1) {
count++;
}
}
cout << count;
}
模拟目录管理功能
#include <cstdio>
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
struct dir {
string name;
map<string, dir*>child;
dir* father;
};
int main() {
string s;
string res = "/";
dir* root = new dir;
root->name = "";
root->father = nullptr;
dir* temp = root;
while (getline(cin, s)) {
if (s.substr(0, 5) == "mkdir") {
dir* newdir = new dir;
newdir->name = s.substr(6, s.size());
if (temp->child.count(newdir->name) == 0) {
newdir->father = temp;
temp->child[newdir->name] = newdir;
}
res = "/";
}
else if (s.substr(0, 2) == "cd") {
string name = s.substr(3, s.size());
if (name == "..") {
if (temp->father != nullptr) {
temp = temp->father;
}
}
else {
if (temp->child.count(name) > 0) {
temp = temp->child[name];
}
}
res = '/';
}
else if (s == "pwd") {
dir* current = temp;
while (current->father != nullptr) {
res = "/" + current->name + res;
current = current->father;
}
}
}
cout << res;
}
特殊的加密算法
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int n;
int m;
vector<int> start;
vector<vector<int>> offset = { {-1, 0}, {0, -1}, {0, 1}, {1, 0} };
vector<int> path;
bool dfs(int x, int y, int index, vector<vector<int>> password, vector<int> data, vector<bool>& used) {
if (index == n) {
return true;
}
for (int i = 0; i < 4; ++i) {
int newx = x + offset[i][0];
int newy = y + offset[i][1];
int v = newx * m + newy;
if (newx < 0 || newx >= m || newy < 0 || newy >= m || used[v] ||
password[newx][newy] != data[index]) {
continue;
}
used[v] = true;
path.push_back(v);
if (dfs(newx, newy, index + 1, password, data, used)) {
return true;
}
used[v] = false;
path.pop_back();
}
return false;
}
int main() {
cin >> n;
vector<int> data(n);
for (int i = 0; i < n; ++i) {
cin >> data[i];
}
cin >> m;
vector<vector<int>> password(m, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
cin >> password[i][j];
if (password[i][j] == data[0]) {
start.push_back(i * m + j);
}
}
}
for (int i = 0; i < start.size(); ++i) {
int x = start[i] / m;
int y = start[i] % m;
vector<bool> used(m * m, false);
used[start[i]] = true;
path.push_back(start[i]);
if (dfs(x, y, 1, password, data, used)) {
for (int i = 0; i < path.size(); ++i) {
int pos = path[i];
cout << pos / m << " " << pos % m;
if (i < path.size() - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
path.clear();
}
cout << "error";
}
田忌赛马

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> a;
vector<int> b;
vector<int> used;
int maxcount = 0;
int res = 0;
void dfs(int index, int n, int cnt){
if(index == n){
if(cnt > maxcount){
maxcount = cnt;
res = 1;
}
else if(cnt == maxcount){
res++;
}
}
for(int i = 0; i < n; ++i){
if(used[i]){
continue;
}
if(i > 0 && a[i] == a[i - 1] && !used[i - 1]){
continue;
}
used[i] = true;
dfs(index + 1, n, cnt + ((a[i] > b[index]) ? 1 : 0));
used[i] = false;
}
}
int main() {
vector<int> nums;
int num;
while (cin >> num) {
nums.push_back(num);
}
int n = nums.size() / 2;
for(int i = 0; i < n; ++i){
a.push_back(nums[i]);
used.push_back(0);
}
for(int i = n; i < 2 * n; ++i){
b.push_back(nums[i]);
}
sort(a.begin(), a.end());
dfs(0, n, 0);
cout << res;
}
最长子字符串的长度(二)

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;
int getResult(const string& s) {
int status = 0b000;
const int numStates = 8;
vector<vector<int>> map(numStates);
map[0].push_back(-1);
int maxLen = 0;
int n = s.size();
for (int i = 0; i < n * 2; ++i) {
char c = s[i % n];
if (c == 'l') {
status ^= 0b100;
} else if (c == 'o') {
status ^= 0b010;
} else if (c == 'x') {
status ^= 0b001;
}
if (i < n) {
map[status].push_back(i);
}
while (!map[status].empty()) {
int earliest = map[status].front();
if (i - earliest > n) {
map[status].erase(map[status].begin());
} else {
maxLen = max(maxLen, i - earliest);
break;
}
}
}
return maxLen;
}
int main() {
string s;
getline(cin, s);
cout << getResult(s) << endl;
return 0;
}
考古学家m
#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;
int n;
vector<string> vec;
set<string> res;
vector<bool> used;
void dfs(int first, string path){
if(first == n){
res.insert(path);
return;
}
for(int i = 0; i < n; ++i){
if(used[i]){
continue;
}
if(i > 0 && vec[i] == vec[i - 1] && !used[i - 1]){
continue;
}
used[i] = true;
dfs(first + 1, path + vec[i]);
used[i] = false;
}
}
int main() {
cin >> n;
for(int i = 0; i < n; ++i){
used.push_back(false);
}
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
vec.push_back(s);
}
sort(vec.begin(), vec.end());
dfs(0, "");
for (auto it = res.begin(); it != res.end(); ++it) {
cout << *it << endl;
}
}
最大社交距离

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> split(string s, char ch) {
stringstream ss;
string token;
vector<int> res;
while (getline(ss, token, ch)) {
res.push_back(stoi(token));
}
return res;
}
int main() {
int n;
cin >> n;
vector<int> seat(n);
vector<int> operate;
string s;
getline(cin, s);
getline(cin, s);
int p = 1;
while (s[p] != ']') {
string numstr;
while ((s[p] >= '0' && s[p] <= '9') || s[p] == '-') {
numstr += s[p];
++p;
}
if (!numstr.empty()) {
operate.push_back(stoi(numstr));
}
if (s[p] == ']') {
break;
}
++p;
}
int res = 0;
seat[0] = 1;
for (int i = 1; i < operate.size(); ++i) {
if (operate[i] < 0) {
int num = -operate[i];
seat[num] = 0;
}
else if (operate[i] == 1) {
int pre = 0;
int emptycount = 0;
int maxdistance = -1;
int j = 1;
for (; j < n; ++j) {
if (seat[j] == 0) {
emptycount++;
}
else {
if (emptycount >= 1 && maxdistance < (emptycount - 1) / 2) {
maxdistance = (emptycount - 1) / 2;
res = (pre + j) / 2;
}
pre = j;
emptycount = 0;
}
}
if (maxdistance == -1 && emptycount == 0) {
res = -1;
break;
}
if (j == n && emptycount != 0) {
if (emptycount - 1 > maxdistance) {
res = n - 1;
}
}
seat[res] = 1;
}
}
cout << res;
}
文本统计分析m
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main(){
string line;
string lines;
while(getline(cin, line)){
lines += line + '\n';
}
int n = lines.size();
int i = 0;
bool flag1 = false;
bool flag2 = false;
int content_length = 0;
int res = 0;
while(i < n){
char ch = lines[i];
switch (ch) {
case '\\':
i++;
break;
case '\"':
if(!flag1){
flag2 = !flag2;
}
content_length++;
break;
case '\'':
if(!flag2){
flag1 = !flag1;
}
content_length++;
break;
case '-':
if(!flag1 && !flag2 && i + 1 < n && lines[i + 1] == '-'){
while(lines[i] != '\n' && i < n){
++i;
}
}
break;
case ';':
if(!flag1 && !flag2 && content_length > 0){
res++;
content_length = 0;
}
break;
default:
if(!isspace(ch)){
content_length++;
}
break;
}
++i;
}
if(content_length > 0){
res++;
}
cout << res;
}
信道分配 not
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 将信道的阶数和数量转化为容量列表
vector<int> getChannelCapacities(const vector<int>& N) {
vector<int> capacities;
for (size_t i = 0; i < N.size(); ++i) {
int capacity = 1 << i;
for (int j = 0; j < N[i]; ++j) {
capacities.push_back(capacity);
}
}
return capacities;
}
// 计算最多可以为多少个用户分配信道
int maxUsers(const vector<int>& capacities, int D) {
vector<int> sortedCapacities = capacities;
sort(sortedCapacities.begin(), sortedCapacities.end(), greater<int>());
int userCount = 0;
while (true) {
int sum = 0;
vector<int> used;
for (int cap : sortedCapacities) {
if (sum >= D) break;
if (cap <= D - sum) {
sum += cap;
used.push_back(cap);
}
}
if (sum < D) break;
++userCount;
for (int cap : used) {
auto it = find(sortedCapacities.begin(), sortedCapacities.end(), cap);
if (it != sortedCapacities.end()) {
sortedCapacities.erase(it);
}
}
}
return userCount;
}
int main() {
int R;
cin >> R;
vector<int> N(R + 1);
for (int i = 0; i <= R; ++i) {
cin >> N[i];
}
int D;
cin >> D;
vector<int> capacities = getChannelCapacities(N);
cout << maxUsers(capacities, D) << endl;
return 0;
}
欢乐的周末v
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// 方向偏移量:上下左右
const vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// BFS函数,找到连通分量
void bfs(int start, const vector<vector<int>>& matrix, vector<int>& component, vector<vector<bool>>& visited) {
int m = matrix.size();
int n = matrix[0].size();
queue<int> q;
q.push(start);
visited[start / n][start % n] = true;
component.push_back(start);
while (!q.empty()) {
int current = q.front();
q.pop();
int x = current / n;
int y = current % n;
for (const auto& dir : directions) {
int newX = x + dir.first;
int newY = y + dir.second;
if (newX >= 0 && newX < m && newY >= 0 && newY < n && !visited[newX][newY] && matrix[newX][newY] != 1) {
visited[newX][newY] = true;
q.push(newX * n + newY);
component.push_back(newX * n + newY);
}
}
}
}
int main() {
int m, n;
cin >> m >> n;
vector<vector<int>> matrix(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> matrix[i][j];
}
}
vector<vector<bool>> visited(m, vector<bool>(n, false));
vector<int> huawei;
vector<int> restaurants;
// 遍历矩阵,记录小华、小为的位置和餐厅的位置
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int pos = i * n + j;
if (matrix[i][j] == 2) {
huawei.push_back(pos);
} else if (matrix[i][j] == 3) {
restaurants.push_back(pos);
}
}
}
// 存储小华、小为所在的连通分量
vector<int> huawei_component;
vector<int> wei_component;
// 如果没有找到两个位置,小华和小为的连接情况是不可行的
if (huawei.size() < 2) {
cout << "0" << endl;
return 0;
}
// 对小华的位置进行BFS,找到小华的连通分量
bfs(huawei[0], matrix, huawei_component, visited);
// 如果小为的位置在小华的连通分量中
if (!visited[huawei[1] / n][huawei[1] % n]) {
cout << "0" << endl;
return 0;
}
// 重新清除visited矩阵以便找到所有餐厅
visited = vector<vector<bool>>(m, vector<bool>(n, false));
// 对小华的位置进行BFS,找出所有在同一连通分量的餐厅
vector<int> huawei_component_restaurants;
for (const int& pos : huawei_component) {
int x = pos / n;
int y = pos % n;
visited[x][y] = true;
if (matrix[x][y] == 3) {
huawei_component_restaurants.push_back(pos);
}
}
// 计算可以去的餐厅数量
int ans = 0;
for (const int& rest : restaurants) {
if (find(huawei_component.begin(), huawei_component.end(), rest) != huawei_component.end()) {
++ans;
}
}
cout << ans << endl;
return 0;
}
二叉树的广度优先遍历
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <cstdlib>
using namespace std;
// 记录题解
char res[27];
int res_size = 0;
/*!
* 字符串截取(左闭右开)
* @param s 字符串
* @param start 起始位置(包含)
* @param end 结束位置(不包含)
* @return 指定区间的子串
*/
char* subString(const char *s, int start, int end) {
int len = end - start;
char *tmp = (char*) calloc(len + 1, sizeof(char));
strncat(tmp, s + start, len);
return tmp;
}
/*!
* 本方法用于从后序遍历、中序遍历序列中分离出:根,以及其左、右子树的后序、中序遍历序列
* @param post 后序遍历结果
* @param mid 中序遍历结果
* @param queue BFS的执行队列
*/
void devideLR(const char *post, const char *mid, queue<pair<string, string>>& bfsQueue) {
// 后序遍历的最后一个元素就是根
char rootEle = post[strlen(post) - 1];
// 将根加入题解
res[res_size++] = rootEle;
// 在中序遍历中找到根的位置rootIdx,那么该位置左边就是左子树,右边就是右子树
int rootIdx = strchr(mid, rootEle) - mid;
// 左子树长度,左子树是中序遍历的0~rootIdx-1范围,长度为rootIdx
// 如果存在左子树,即左子树长度大于0
if (rootIdx > 0) {
// 则从后序遍历中,截取出左子树的后序遍历
char* leftPost = subString(post, 0, rootIdx);
// 从中序遍历中,截取出左子树的中序遍历
char* leftMid = subString(mid, 0, rootIdx);
// 将左子树的后、中遍历序列加入执行队列
bfsQueue.push({leftPost, leftMid});
// 释放临时字符串
free(leftPost);
free(leftMid);
}
// 如果存在右子树,即右子树长度大于0
if (strlen(post) - 1 - rootIdx > 0) {
// 则从后序遍历中,截取出右子树的后序遍历
char* rightPost = subString(post, rootIdx, strlen(post) - 1);
// 从中序遍历中,截取出右子树的中序遍历
char* rightMid = subString(mid, rootIdx + 1, strlen(mid));
// 将右子树的后、中遍历序列加入执行队列
bfsQueue.push({rightPost, rightMid});
// 释放临时字符串
free(rightPost);
free(rightMid);
}
}
int main() {
// 输入后序遍历和中序遍历序列
char post[27];
char mid[27];
// 读取输入
cin >> post >> mid;
// 广度优先搜索的执行队列
queue<pair<string, string>> bfsQueue;
// 将初始的后序遍历和中序遍历序列加入队列
bfsQueue.push({post, mid});
// 广度优先搜索,层序遍历
while (!bfsQueue.empty()) {
// 取出队首元素
pair<string, string> node = bfsQueue.front();
bfsQueue.pop();
// 进行分割处理
devideLR(node.first.c_str(), node.second.c_str(), bfsQueue);
}
// 输出结果
cout << res << endl;
return 0;
}
图像物体的边界

#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
int a[N][N]; // 存储地图中可到达的位置
int visited[N][N]; // 记录每个位置是否已经被访问过
int n, m; // 地图的行数和列数
// 移动方向:8个方向
int dx[8] = {0, 0, -1, 1, -1, 1, -1, 1};
int dy[8] = {-1, 1, 0, 0, -1, 1, 1, -1};
// 广度优先搜索,用于遍历地图中的连通块
void bfs(int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
visited[x][y] = 1;
while (!q.empty()) {
auto [cx, cy] = q.front();
q.pop();
// 遍历当前位置的所有相邻位置
for (int i = 0; i < 8; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !visited[nx][ny] && a[nx][ny] == 1) {
visited[nx][ny] = 1;
q.push({nx, ny});
}
}
}
}
int main() {
// 读取地图的行数和列数
cin >> n >> m;
// 读取地图信息并初始化a数组
vector<vector<int>> mp(n + 2, vector<int>(m + 2, 0)); // 增加边界
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> mp[i][j];
}
}
// 根据地图信息更新a数组,表示可到达的位置
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp[i][j] == 5) {
// 如果当前位置为5,则更新其周围相邻位置可到达
for (int k = 0; k < 8; k++) {
int ni = i + dx[k];
int nj = j + dy[k];
if (ni >= 1 && ni <= n && nj >= 1 && nj <= m && mp[ni][nj] == 1) {
a[ni][nj] = 1;
}
}
}
}
}
int cnt = 0; // 记录连通块的数量
// 遍历地图中的每个位置
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// 如果当前位置可到达且未被访问过,进行BFS遍历
if (a[i][j] == 1 && !visited[i][j]) {
cnt++; // 连通块数量加1
bfs(i, j); // 对连通块进行BFS遍历
}
}
}
// 输出连通块的数量
cout << cnt << endl;
return 0;
}
数组排列求和 ?
模拟数据序列化传输
学生重新排队
音乐小说内容重复识别
找单词(5oj)

#include<bits/stdc++.h>
using namespace std;
const int N=1010;
char g[N][N];
int n;
string s;
bool vis[N][N];
int dx[4]={-1,1,0,0}, dy[4]={0,0,1,-1};
bool dfs(int cnt, int x, int y, vector<pair<int,int>>& path) {
// 判断是否越界、已访问或者当前位置字符不匹配
if (x < 0 || x >= n || y < 0 || y >= n || vis[x][y] || g[x][y] != s[cnt]) {
return false;
}
// 如果已经找到字符串的最后一个字符,输出路径并返回 true
if (cnt == s.size() - 1) {
int m = path.size();
for (int i = 0; i < m; i++) {
printf("%d,%d", path[i].first, path[i].second);
if (i < m - 1) {
printf(",");
}
}
return true;
}
// 标记当前位置已访问
vis[x][y] = true;
// 遍历四个方向
for (int i = 0; i < 4; i++) {
int a = dx[i] + x;
int b = dy[i] + y;
// 记录路径
path.push_back({a, b});
// 递归调用 dfs
if (dfs(cnt + 1, a, b, path)) {
return true;
}
// 回溯,移除路径
path.pop_back();
}
// 恢复当前位置未访问状态
vis[x][y] = false;
return false;
}
int main() {
scanf("%d\n", &n);
// 读取迷宫字符数组 g
for (int i = 0; i < n; i++) {
string t;
cin >> t;
for (int j = 0; j < n; j++) {
g[i][j] = t[j * 2];
}
}
// 读取目标字符串 s
cin >> s;
// 在迷宫中寻找字符串 s 的路径
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] == s[0]) {
memset(vis, 0, sizeof vis);
vector<pair<int, int>> path = {{i, j}};
if (dfs(0, i, j, path)) {
break;
}
}
}
}
return 0;
}
找城市\

#include <algorithm>
#include <complex>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int n;
vector<int> father;
int find(int x) {
if (x != father[x]) {
father[x] = find(father[x]);
}
return father[x];
}
int main() {
cin >> n;
vector<pair<int, int>> relations;
vector<pair<int, int>> dp(n + 1);
int a, b;
while (cin >> a >> b) {
relations.push_back(make_pair(a, b));
}
for (int i = 0; i <= n; ++i) {
father.push_back(i);
}
for (int i = 1; i <= n; ++i) {
for (int i = 0; i <= n; ++i) {
father[i] = i;
}
for (int j = 0; j < relations.size(); ++j) {
int x = relations[j].first;
int y = relations[j].second;
if (x == i || y == i) {
continue;
}
int root1 = find(x);
int root2 = find(y);
if (root1 != root2) {
father[root2] = root1;
}
}
vector<int> count(n + 1);
for (int j = 1; j <= n; ++j) {
int root = find(j);
count[root]++;
}
dp[i] = make_pair(*max_element(count.begin(), count.end()), i);
}
sort(dp.begin(), dp.end(), [](pair<int, int> a, pair<int, int> b){
if(a.first == b.first){
return a.second < b.second;
}
else{
return a.first < b.first;
}
});
int mindp = dp[1].first;
cout << dp[1].second;
for(int i = 2; i <= n; ++i){
if(dp[i].first > mindp){
break;
}
cout << " " << dp[i].second;
}
}
可以组成网络的服务器

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 定义网格的行数和列数
int n, m;
// 定义网格矩阵和访问标记矩阵
vector<vector<int>> g;
vector<vector<bool>> st;
// 定义四个方向的移动向量
vector<int> dx = {-1, 1, 0, 0};
vector<int> dy = {0, 0, 1, -1};
// 计数器和结果变量
int cnt, res;
void bfs(int startX, int startY) {
queue<pair<int, int>> q;
q.push({startX, startY});
st[startX][startY] = true; // 将起始位置标记为已访问
cnt = 0; // 重置计数器
while (!q.empty()) {
auto [x, y] = q.front(); // 取出队列头部元素
q.pop();
cnt++; // 计数器加1
// 遍历四个方向
for (int d = 0; d < 4; d++) {
int newX = x + dx[d];
int newY = y + dy[d];
// 检查新位置是否在网格内且未访问过
if (newX >= 0 && newX < n && newY >= 0 && newY < m && !st[newX][newY] && g[newX][newY] == 1) {
q.push({newX, newY}); // 将新位置加入队列
st[newX][newY] = true; // 标记新位置为已访问
}
}
}
}
int main() {
cin >> n >> m; // 读取网格的行数和列数
// 调整网格和标记矩阵的大小
g.resize(n, vector<int>(m));
st.resize(n, vector<bool>(m));
// 读取网格的内容
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> g[i][j];
}
}
res = 0; // 初始化结果变量
// 遍历网格,找到所有的单元格并进行广度优先遍历
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 1 && !st[i][j]) { // 如果当前单元格是未访问的陆地
bfs(i, j); // 对当前单元格进行广度优先遍历
res = max(res, cnt); // 更新最大连通块的大小
}
}
}
cout << res << endl; // 输出结果
return 0;
}
简易内存池v
#include <iostream>
#include <map>
#include <sstream>
using namespace std;
const int MAX_MEMORY = 100; // 内存池总大小
map<int, int> memoryMap; // 存储内存分配情况
// 请求分配内存
void request(int size) {
if (size <= 0 || size > MAX_MEMORY) {
cout << "error" << endl;
return;
}
// 特殊情况:如果内存池为空,则直接分配在首地址0
if (memoryMap.empty()) {
memoryMap[0] = size;
cout << 0 << endl;
return;
}
int prevEnd = 0; // 上一个内存块的结束位置
// 遍历内存块,查找合适的空闲空间
for (auto it = memoryMap.begin(); it != memoryMap.end(); ++it) {
int start = it->first;
int end = it->second;
if (start - prevEnd >= size) {
// 找到合适的空闲空间
memoryMap[prevEnd] = prevEnd + size;
cout << prevEnd << endl;
return;
}
prevEnd = end;
}
// 检查内存池末尾是否有足够空间
if (MAX_MEMORY - prevEnd >= size) {
memoryMap[prevEnd] = prevEnd + size;
cout << prevEnd << endl;
} else {
cout << "error" << endl;
}
}
// 释放内存
void release(int address) {
auto it = memoryMap.find(address);
if (it != memoryMap.end()) {
memoryMap.erase(it);
} else {
cout << "error" << endl;
}
}
int main() {
try {
int N;
cin >> N;
cin.ignore(); // 忽略换行符
for (int i = 0; i < N; i++) {
string line;
getline(cin, line);
istringstream iss(line);
string command;
int value;
if (getline(iss, command, '=') && iss >> value) {
if (command == "REQUEST") {
request(value);
} else if (command == "RELEASE") {
release(value);
} else {
cout << "error" << endl;
}
} else {
cout << "error" << endl;
}
}
} catch (const exception& e) {
cout << "error" << endl;
}
return 0;
}
快递员的烦恼
#include <stdio.h>
#include <limits.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX_SIZE 11
#define MAX_ID 1000
int n;
int dist[MAX_SIZE][MAX_SIZE];
int path[MAX_SIZE][MAX_SIZE];
int ans;
/**
* 找一条经过所有点的最短路径,我们可以求解所有点形成的全排列,每一个全排列都对应一条经过所有点的路径,只是经过点的先后顺序不同 //
* 求某个全排列过程中,可以通过dist数组,累计上一个点i到下一个点j的最短路径dist[i][j]
*
* @param pre 上一个点, 初始为0,表示从披萨店出发
* @param sum 当前全排列路径累计的路径权重
* @param used 全排列used数组,用于标记哪些点已使用过
* @param level 用于记录排列的长度
*/
void dfs(int pre, int sum, int used[], int level) {
if (level == n) {
// 此时pre是最后一个客户所在点,送完最后一个客户后,司机需要回到披萨店,因此最终累计路径权重为 sum + dist[pre][0]
// 我们保留最小权重路径
ans = MIN(ans, sum + dist[pre][0]);
return;
}
for (int i = 1; i <= n; i++) {
if (used[i]) continue;
used[i] = 1;
dfs(i, sum + dist[pre][i], used, level + 1);
used[i] = 0;
}
}
// floyd算法求解图中任意两点之间的最短路径
void floyd() {
for (int k = 0; k < n + 1; k++) {
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n + 1; j++) {
// newDist是经过k后,i->j的距离
int newDist = dist[i][k] + dist[k][j];
// 如果newDist是i->j的更短路径
if (newDist < dist[i][j]) {
// 则更新i->j的最短距离
dist[i][j] = newDist;
// 且此更短距离需要经过k, path[i][j]即记录 i->j 最短距离下需要经过点 k
path[i][j] = k;
}
}
}
}
}
int main() {
int m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n + 1; j++) {
// 初始时默认i,j不相连,即i,j之间距离无穷大
if (i != j) {
dist[i][j] = INT_MAX;
}
path[i][j] = -1;
}
}
// 由于本题的客户id不是顺序的,因此这里需要将客户id离散化处理
int map[MAX_ID];
for (int i = 1; i <= n; i++) {
int id, dis;
scanf("%d %d", &id, &dis);
// 离散化处理
map[id] = i;
// 投递站到客户之间的距离distance
dist[0][i] = dis;
dist[i][0] = dis;
}
for (int i = 1; i <= m; i++) {
int id1, id2, dis;
scanf("%d %d %d", &id1, &id2, &dis);
int i1 = map[id1];
int i2 = map[id2];
// 客户与客户之间的距离信息
dist[i1][i2] = dis;
dist[i2][i1] = dis;
}
// floyd算法调用
floyd();
// ans记录经过所有点后回到出发点的最短距离
ans = INT_MAX;
// 全排列模拟经过所有点的路径
int used[MAX_SIZE] = {0};
dfs(0, 0, used, 0);
printf("%d\n", ans);
}
查找一个有向网络的头节点和尾节点
#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
if(n == 0){
cout << -1;
return 0;
}
map<int, int> indegree;
map<int, vector<int>> next;
set<int> node;
for(int i = 0; i < n; ++i){
int a, b;
cin >> a >> b;
node.insert(a);
node.insert(b);
indegree[b]++;
next[a].push_back(b);
}
int count = node.size();
int head = 0;
deque<int> q;
for(auto it = node.begin(); it != node.end(); ++it){
if(indegree.count(*it) == 0){
head = *it;
q.push_back(head);
break;
}
}
vector<int> tails;
int curcnt = 0;
while(!q.empty()){
int v = q.front();
q.pop_front();
curcnt++;
if(next.count(v) == 0){
tails.push_back(v);
continue;
}
vector<int> child = next[v];
for(int i = 0; i < child.size(); ++i){
int u = child[i];
indegree[u]--;
if(indegree[u] == 0){
q.push_back(u);
}
}
}
if(curcnt != count){
cout << -1 << endl;
}
else{
cout << head << " ";
sort(tails.begin(), tails.end());
for(int i = 0; i < tails.size(); ++i){
cout << tails[i] << " ";
}
}
}

浙公网安备 33010602011771号