引言:C++算法设计的核心价值
在现代软件开发中,算法设计是区分普通程序员和优秀工程师的关键能力。C++作为一门兼具高性能和抽象能力的编程语言,为算法实现提供了强大的支持。掌握C++算法设计技巧不仅能提升代码效率,更能培养系统性的编程思维。
本文将从基础概念入手,逐步深入到高级技巧,涵盖递归、分治、动态规划、贪心算法、图算法等核心内容,并结合实际代码示例,帮助读者建立完整的算法知识体系。
一、基础算法思维:从暴力到优化
1.1 暴力枚举与优化思路
暴力枚举(Brute Force)是算法设计的起点。虽然效率较低,但它是理解问题和验证思路的基础。
示例:计算1到n的阶乘
#include
#include
// 暴力方法:直接计算每个数的阶乘
std::vector
std::vector
result[0] = 1;
for (int i = 1; i <= n; ++i) {
long long fact = 1;
for (int j = 1; j <= i; ++j) {
fact *= j;
}
result[i] = fact;
}
return result;
}
// 优化方法:利用递推关系
std::vector
std::vector
result[0] = 1;
for (int i = 1; i <= n; ++i) {
result[i] = result[i - 1] * i; // 利用已计算的结果
}
return result;
}
优化分析
:
暴力方法时间复杂度:O(n²)
优化后时间复杂度:O(n)
空间复杂度均为O(n)
1.2 时间复杂度与空间复杂度分析
算法效率分析是设计优化的基础。我们需要掌握:
时间复杂度
:算法执行时间随输入规模的增长趋势
空间复杂度
:算法所需内存空间随输入规模的增长趋势
常见复杂度对比
:
O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!)
1.3 前缀和与差分数组
前缀和是处理区间查询问题的利器,差分数组则适合区间更新。
前缀和示例:区间求和
#include
#include
class PrefixSum {
private:
std::vector
public:
// 构造函数:O(n)
PrefixSum(const std::vector
prefix.resize(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); ++i) {
prefix[i + 1] = prefix[i] + nums[i];
}
}
// 查询区间和:O(1)
int rangeSum(int left, int right) {
return prefix[right + 1] - prefix[left];
}
};
// 使用示例
int main() {
std::vector
PrefixSum ps(nums);
std::cout << "Sum[1,3]: " << ps.rangeSum(1, 3) << std::endl; // 输出 9
return 0;
}
差分数组示例:区间更新
#include
#include
class DifferenceArray {
private:
std::vector
public:
DifferenceArray(const std::vector
diff.resize(nums.size(), 0);
diff[0] = nums[0];
for (int i = 1; i < nums.size(); ++i) {
diff[i] = nums[i] - nums[i - 1];
}
}
// 区间更新:[left, right]增加val
void increment(int left, int right, int val) {
diff[left] += val;
if (right + 1 < diff.size()) {
diff[right + 1] -= val;
}
}
// 还原原数组
std::vector
std::vector
res[0] = diff[0];
for (int i = 1; i < diff.size(); ++i) {
res[i] = res[i - 1] + diff[i];
}
return res;
}
};
// 使用示例
int main() {
std::vector
DifferenceArray da(nums);
da.increment(1, 3, 10); // [2,3,4]各加10
std::vector
for (int val : result) {
std::cout << val << " "; // 输出: 1 12 13 14 5
}
return 0;
}
二、递归与分治:化繁为简的艺术
2.1 递归基础与栈溢出防护
递归是将大问题分解为小问题的优雅方式,但需要注意栈溢出问题。
示例:斐波那契数列
#include
#include
#include
// 普通递归:指数级时间复杂度
int fib_recursive(int n) {
if (n <= 1) return n;
return fib_recursive(n - 1) + fib_recursive(n - 2);
}
// 带备忘录的递归(记忆化搜索):O(n)
int fib_memo(int n, std::unordered_map
if (n <= 1) return n;
if (memo.find(n) != memo.end()) return memo[n];
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo);
return memo[n];
}
// 迭代法(动态规划):O(n),空间优化
int fib_iterative(int n) {
if (n <= 1) return n;
int prev = 0, curr = 1;
for (int i = 2; i <= n; ++i) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
// 尾递归优化(编译器支持时)
int fib_tail_recursive(int n, int a = 0, int b = 1) {
if (n == 0) return a;
if (n == 1) return b;
return fib_tail_recursive(n - 1, b, a + b);
}
性能对比
:
普通递归:O(2ⁿ) 时间,O(n) 空间(栈深度)
记忆化递归:O(n) 时间,O(n) 空间
迭代法:O(n) 时间,O(1) 空间
尾递归:O(n) 时间,O(1) 空间(编译器优化后)
2.2 分治算法:归并排序与快速排序
分治算法通过”分-治-合”三步解决问题。
归并排序示例
:
#include
#include
class MergeSort {
public:
void sort(std::vector
if (nums.size() <= 1) return;
mergeSort(nums, 0, nums.size() - 1);
}
private:
void mergeSort(std::vector
if (left >= right) return;
int mid = left + (right – left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
void merge(std::vector
std::vector
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
}
}
while (i <= mid) temp[k++] = nums[i++];
while (j <= right) temp[k++] = nums[j++];
for (int p = 0; p < temp.size(); ++p) {
nums[left + p] = temp[p];
}
}
};
快速排序示例
:
#include
#include
#include
class QuickSort {
public:
void sort(std::vector
if (nums.size() <= 1) return;
quickSort(nums, 0, nums.size() - 1);
}
private:
void quickSort(std::vector
if (left >= right) return;
int pivotIndex = partition(nums, left, right);
quickSort(nums, left, pivotIndex – 1);
quickSort(nums, pivotIndex + 1, right);
}
int partition(std::vector
// 三数取中法选择pivot,避免最坏情况
int mid = left + (right – left) / 2;
if (nums[left] > nums[mid]) std::swap(nums[left], nums[mid]);
if (nums[mid] > nums[right]) std::swap(nums[mid], nums[right]);
if (nums[left] > nums[mid]) std::swap(nums[left], nums[mid]);
int pivot = nums[mid];
std::swap(nums[mid], nums[right]); // 将pivot放到末尾
int storeIndex = left;
for (int i = left; i < right; ++i) {
if (nums[i] < pivot) {
std::swap(nums[i], nums[storeIndex]);
storeIndex++;
}
}
std::swap(nums[storeIndex], nums[right]); // 将pivot放到正确位置
return storeIndex;
}
};
分治算法复杂度分析
:
归并排序:时间O(n log n),空间O(n)
快速排序:平均时间O(n log n),最坏O(n²),空间O(log n)栈空间
2.3 二分查找及其变种
二分查找是分治思想的典型应用,要求数据有序。
标准二分查找
:
#include
#include
class BinarySearch {
public:
// 查找target首次出现的位置
int lowerBound(const std::vector
int left = 0, right = nums.size() – 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid – 1;
} else {
left = mid + 1;
}
}
return left; // left是第一个>=target的位置
}
// 查找target最后出现位置的下一个位置
int upperBound(const std::vector
int left = 0, right = nums.size() – 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left; // left是第一个>target的位置
}
// 查找精确位置
int find(const std::vector
int left = 0, right = nums.size() – 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
};
二分查找的变种应用
:
// 在旋转排序数组中查找
int searchInRotatedArray(const std::vector
int left = 0, right = nums.size() – 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
// 左半部分有序
if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else { // 右半部分有序
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
三、动态规划:从状态定义到优化
3.1 动态规划核心要素
动态规划(DP)解决重叠子问题,需要满足:
最优子结构
:问题的最优解包含子问题的最优解
重叠子问题
:子问题被重复计算
状态转移方程
:定义dp[i]的含义和递推关系
3.2 0-1背包问题详解
问题描述
:给定物品重量weights和价值values,背包容量W,求最大价值。
#include
#include
#include
class Knapsack {
public:
// 二维DP:dp[i][w]表示前i个物品在容量w下的最大价值
int knapsack2D(const std::vector
int n = weights.size();
std::vector
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
if (weights[i - 1] <= w) {
dp[i][w] = std::max(
dp[i - 1][w], // 不选当前物品
dp[i - 1][w - weights[i - 1]] + values[i - 1] // 选当前物品
);
} else {
dp[i][w] = dp[i - 1][w]; // 当前物品太重,无法选择
}
}
}
return dp[n][W];
}
// 一维DP优化:空间优化
int knapsack1D(const std::vector
std::vector
for (int i = 0; i < weights.size(); ++i) {
// 必须从后往前遍历,避免重复使用当前物品
for (int w = W; w >= weights[i]; –w) {
dp[w] = std::max(dp[w], dp[w – weights[i]] + values[i]);
}
}
return dp[W];
}
// 完全背包:物品可以无限取用
int unboundedKnapsack(const std::vector
std::vector
for (int i = 0; i < weights.size(); ++i) {
// 从前往后遍历,允许重复使用当前物品
for (int w = weights[i]; w <= W; ++w) {
dp[w] = std::max(dp[w], dp[w - weights[i]] + values[i]);
}
}
return dp[W];
}
};
3.3 最长公共子序列(LCS)
问题描述
:求两个字符串的最长公共子序列长度。
#include
#include
#include
#include
class LCS {
public:
int longestCommonSubsequence(const std::string& text1, const std::string& text2) {
int m = text1.size(), n = text2.size();
std::vector
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
// 输出具体的LCS
std::string getLCS(const std::string& text1, const std::string& text2) {
int m = text1.size(), n = text2.size();
std::vector
// 填充dp表
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// 回溯构造LCS
std::string lcs;
int i = m, j = n;
while (i > 0 && j > 0) {
if (text1[i – 1] == text2[j – 1]) {
lcs = text1[i – 1] + lcs;
–i; –j;
} else if (dp[i – 1][j] > dp[i][j – 1]) {
–i;
} else {
–j;
}
}
return lcs;
}
};
3.4 状态压缩DP
当状态可以用二进制表示时,可以使用状态压缩DP。
示例:旅行商问题(TSP)的简化版
#include
#include
#include
#include
class TSP {
public:
int solve(const std::vector
int n = dist.size();
int totalStates = 1 << n;
// dp[mask][i]表示访问过mask表示的点集,最后在i点的最小距离
std::vector
// 初始状态:从0点出发
dp[1][0] = 0;
for (int mask = 1; mask < totalStates; ++mask) {
for (int i = 0; i < n; ++i) {
if (dp[mask][i] == INT_MAX) continue;
for (int j = 0; j < n; ++j) {
if (mask & (1 << j)) continue; // j已访问
int newMask = mask | (1 << j);
dp[newMask][j] = std::min(dp[newMask][j], dp[mask][i] + dist[i][j]);
}
}
}
// 回到起点
int fullMask = totalStates - 1;
int minDist = INT_MAX;
for (int i = 1; i < n; ++i) {
minDist = std::min(minDist, dp[fullMask][i] + dist[i][0]);
}
return minDist;
}
};
3.5 记忆化搜索 vs 迭代DP
记忆化搜索(自顶向下)
:
#include
#include
#include
class MemoDP {
public:
int climbStairs(int n) {
std::unordered_map
return helper(n, memo);
}
private:
int helper(int n, std::unordered_map
if (n <= 2) return n;
if (memo.find(n) != memo.end()) return memo[n];
memo[n] = helper(n - 1, memo) + helper(n - 2, memo);
return memo[n];
}
};
迭代DP(自底向上)
:
class IterativeDP {
public:
int climbStairs(int n) {
if (n <= 2) return n;
std::vector
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// 空间优化:只保留前两个状态
int climbStairsOptimized(int n) {
if (n <= 2) return n;
int prev = 1, curr = 2;
for (int i = 3; i <= n; ++i) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
};
四、贪心算法:局部最优的选择
4.1 贪心算法适用条件
贪心算法通过每一步的局部最优选择达到全局最优,适用于具有贪心选择性质和最优子结构的问题。
4.2 区间调度问题
问题描述
:给定多个区间[start, end],选择最多数量的互不重叠区间。
#include
#include
#include
struct Interval {
int start, end;
Interval(int s, int e) : start(s), end(e) {}
};
class IntervalScheduling {
public:
int maxNonOverlappingIntervals(std::vector
// 按结束时间排序
std::sort(intervals.begin(), intervals.end(),
[](const Interval& a, const Interval& b) {
return a.end < b.end;
});
int count = 0;
int lastEnd = -1;
for (const auto& interval : intervals) {
if (interval.start >= lastEnd) {
count++;
lastEnd = interval.end;
}
}
return count;
}
};
4.3 霍夫曼编码
霍夫曼编码是经典的贪心应用,用于数据压缩。
#include
#include
#include
#include
struct HuffmanNode {
char ch;
int freq;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
class HuffmanCoding {
public:
// 自定义比较器
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
std::unordered_map
// 统计频率
std::unordered_map
for (char ch : text) {
freq[ch]++;
}
// 构建优先队列
std::priority_queue
for (const auto& [ch, f] : freq) {
pq.push(new HuffmanNode(ch, f));
}
// 构建Huffman树
while (pq.size() > 1) {
HuffmanNode* left = pq.top(); pq.pop();
HuffmanNode* right = pq.top(); pq.pop();
HuffmanNode* parent = new HuffmanNode(‘\0’, left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
// 生成编码
std::unordered_map
if (!pq.empty()) {
generateCodes(pq.top(), “”, codes);
}
return codes;
}
private:
void generateCodes(HuffmanNode* node, const std::string& code,
std::unordered_map
if (!node) return;
if (!node->left && !node->right) {
codes[node->ch] = code;
return;
}
generateCodes(node->left, code + “0”, codes);
generateCodes(node->right, code + “1”, codes);
}
};
4.4 贪心 vs 动态规划
经典对比:找零钱问题
// 贪心算法:仅适用于特定面额(如1,5,10,25)
int greedyCoinChange(const std::vector
std::vector
std::sort(coins.rbegin(), coins.rend()); // 从大到小
for (int coin : coins) {
while (amount >= coin) {
result.push_back(coin);
amount -= coin;
}
}
return result.size();
}
// 动态规划:适用于任意面额
int dpCoinChange(const std::vector
std::vector
dp[0] = 0;
for (int i = 1; i <= amount; ++i) {
for (int coin : coins) {
if (i >= coin) {
dp[i] = std::min(dp[i], dp[i – coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
五、图算法:从遍历到最短路径
5.1 图的表示方式
邻接矩阵
:
std::vector
adjMatrix[u][v] = weight;
邻接表
:
std::vector
adjList[u].push_back({v, weight});
5.2 深度优先搜索(DFS)
#include
#include
#include
class DFS {
public:
// 递归实现
void dfsRecursive(int node, std::vector
const std::vector
visited[node] = true;
std::cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfsRecursive(neighbor, visited, graph);
}
}
}
// 迭代实现(使用栈)
void dfsIterative(int start, const std::vector
std::vector
std::stack
st.push(start);
while (!st.empty()) {
int node = st.top();
st.pop();
if (!visited[node]) {
visited[node] = true;
std::cout << node << " ";
// 注意:需要逆序入栈以保持递归顺序
for (auto it = graph[node].rbegin(); it != graph[node].rend(); ++it) {
if (!visited[*it]) {
st.push(*it);
}
}
}
}
}
};
5.3 广度优先搜索(BFS)
#include
#include
#include
class BFS {
public:
void bfs(int start, const std::vector
std::vector
std::queue
q.push(start);
visited[start] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
std::cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
// BFS求最短路径(无权图)
std::vector
const std::vector
int n = graph.size();
std::vector
std::vector
std::queue
q.push(start);
visited[start] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
if (node == end) break;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
parent[neighbor] = node;
q.push(neighbor);
}
}
}
// 重建路径
std::vector
if (!visited[end]) return path; // 不可达
for (int v = end; v != -1; v = parent[v]) {
path.push_back(v);
}
std::reverse(path.begin(), path.end());
return path;
}
};
5.4 Dijkstra算法(单源最短路径)
#include
#include
#include
#include
class Dijkstra {
public:
std::vector
const std::vector
int n = graph.size();
std::vector
dist[start] = 0;
// 优先队列:{距离, 节点}
std::priority_queue
std::vector
std::greater
pq.push({0, start});
while (!pq.empty()) {
auto [d, node] = pq.top();
pq.pop();
// 如果找到更短路径,跳过
if (d > dist[node]) continue;
for (auto& [neighbor, weight] : graph[node]) {
if (dist[node] + weight < dist[neighbor]) {
dist[neighbor] = dist[node] + weight;
pq.push({dist[neighbor], neighbor});
}
}
}
return dist;
}
};
5.5 拓扑排序
#include
#include
#include
class TopologicalSort {
public:
std::vector
const std::vector
std::vector
std::vector
// 构建图和入度数组
for (const auto& edge : prerequisites) {
graph[edge[1]].push_back(edge[0]);
indegree[edge[0]]++;
}
// Kahn算法
std::queue
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) {
q.push(i);
}
}
std::vector
while (!q.empty()) {
int node = q.front();
q.pop();
result.push_back(node);
for (int neighbor : graph[node]) {
indegree[neighbor]–;
if (indegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
return result.size() == numCourses ? result : std::vector
}
};
5.6 最小生成树(Prim和Kruskal)
Prim算法
:
#include
#include
#include
#include
class Prim {
public:
int minSpanningTree(const std::vector
int n = graph.size();
std::vector
std::vector
std::priority_queue
std::vector
std::greater
key[0] = 0;
pq.push({0, 0});
int mstWeight = 0;
while (!pq.empty()) {
auto [weight, node] = pq.top();
pq.pop();
if (inMST[node]) continue;
inMST[node] = true;
mstWeight += weight;
for (auto& [neighbor, w] : graph[node]) {
if (!inMST[neighbor] && w < key[neighbor]) {
key[neighbor] = w;
pq.push({w, neighbor});
}
}
}
return mstWeight;
}
};
Kruskal算法
:
#include
#include
#include
class UnionFind {
private:
std::vector
std::vector
public:
UnionFind(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; ++i) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // 路径压缩
}
return parent[x];
}
bool unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return false;
// 按秩合并
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
return true;
}
};
class Kruskal {
public:
struct Edge {
int u, v, weight;
Edge(int u, int v, int w) : u(u), v(v), weight(w) {}
};
int minSpanningTree(int n, std::vector
// 按权重排序
std::sort(edges.begin(), edges.end(),
[](const Edge& a, const Edge& b) {
return a.weight < b.weight;
});
UnionFind uf(n);
int mstWeight = 0;
int edgesUsed = 0;
for (const auto& edge : edges) {
if (uf.unite(edge.u, edge.v)) {
mstWeight += edge.weight;
edgesUsed++;
if (edgesUsed == n - 1) break;
}
}
return edgesUsed == n - 1 ? mstWeight : -1;
}
};
六、高级技巧与优化策略
6.1 双指针技术
双指针常用于数组和链表问题,能将O(n²)优化到O(n)。
示例:两数之和
#include
#include
#include
class TwoPointer {
public:
// 有序数组两数之和
std::pair
int left = 0, right = nums.size() – 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) return {left, right};
if (sum < target) left++;
else right--;
}
return {-1, -1};
}
// 三数之和
std::vector
std::sort(nums.begin(), nums.end());
std::vector
for (int i = 0; i < nums.size() - 2; ++i) { if (i > 0 && nums[i] == nums[i – 1]) continue; // 去重
int left = i + 1, right = nums.size() – 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
// 去重
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
// 滑动窗口:最小覆盖子串
std::string minWindow(const std::string& s, const std::string& t) {
std::vector
for (char c : t) need[c]++;
int left = 0, right = 0;
int count = 0;
int minLen = INT_MAX;
int start = 0;
while (right < s.size()) {
char c = s[right];
if (need[c] > 0) count++;
need[c]–;
right++;
while (count == t.size()) {
if (right – left < minLen) {
minLen = right - left;
start = left;
}
char d = s[left];
need[d]++;
if (need[d] > 0) count–;
left++;
}
}
return minLen == INT_MAX ? “” : s.substr(start, minLen);
}
};
6.2 滑动窗口
滑动窗口是双指针的扩展,用于处理连续子数组/子串问题。
#include
#include
#include
class SlidingWindow {
public:
// 最长无重复子串
int lengthOfLongestSubstring(const std::string& s) {
std::unordered_map
int left = 0, right = 0;
int maxLen = 0;
while (right < s.size()) {
char c = s[right];
right++;
window[c]++;
while (window[c] > 1) {
char d = s[left];
left++;
window[d]–;
}
maxLen = std::max(maxLen, right – left);
}
return maxLen;
}
// 长度为k的子数组的最大和
int maxSum(const std::vector
if (nums.size() < k) return 0;
int windowSum = 0;
for (int i = 0; i < k; ++i) {
windowSum += nums[i];
}
int maxSum = windowSum;
for (int i = k; i < nums.size(); ++i) {
windowSum += nums[i] - nums[i - k];
maxSum = std::max(maxSum, windowSum);
}
return maxSum;
}
};
6.3 位运算技巧
位运算在算法竞赛中常用于优化和状态表示。
#include
#include
class BitTricks {
public:
// 快速幂:计算(base^exp) % mod
long long fastPower(long long base, long long exp, long long mod) {
long long result = 1;
base %= mod;
while (exp > 0) {
if (exp & 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp >>= 1;
}
return result;
}
// 判断是否是2的幂
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n – 1)) == 0;
}
// 计算汉明权重(1的个数)
int hammingWeight(int n) {
int count = 0;
while (n) {
n &= (n – 1); // 清除最低位的1
count++;
}
return count;
}
// 交换两个数(不使用临时变量)
void swap(int& a, int& b) {
a ^= b;
b ^= a;
a ^= b;
}
// 找到唯一出现一次的数字(其他都出现两次)
int singleNumber(const std::vector
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
// 找到唯一出现一次的数字(其他都出现三次)
int singleNumberThreeTimes(const std::vector
int ones = 0, twos = 0;
for (int num : nums) {
ones = (ones ^ num) & ~twos;
twos = (twos ^ num) & ~ones;
}
return ones;
}
};
6.4 并查集(Union-Find)
并查集用于处理动态连通性问题。
#include
#include
#include
class UnionFindOptimized {
private:
std::vector
std::vector
std::vector
public:
UnionFindOptimized(int n) {
parent.resize(n);
std::iota(parent.begin(), parent.end(), 0);
rank.resize(n, 0);
size.resize(n, 1);
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // 路径压缩
}
return parent[x];
}
bool unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return false;
// 按秩合并(按大小)
if (size[rootX] < size[rootY]) {
std::swap(rootX, rootY);
}
parent[rootY] = rootX;
size[rootX] += size[rootY];
rank[rootX] = std::max(rank[rootX], rank[rootY] + 1);
return true;
}
bool connected(int x, int y) {
return find(x) == find(y);
}
int componentSize(int x) {
return size[find(x)];
}
};
6.5 单调栈与单调队列
单调栈:下一个更大元素
#include
#include
#include
class MonotonicStack {
public:
std::vector
int n = nums.size();
std::vector
std::stack
// 两次遍历处理循环数组
for (int i = 0; i < 2 * n; ++i) {
int num = nums[i % n];
while (!st.empty() && nums[st.top()] < num) {
result[st.top()] = num;
st.pop();
}
if (i < n) {
st.push(i);
}
}
return result;
}
};
单调队列:滑动窗口最大值
#include
#include
#include
class MonotonicQueue {
public:
std::vector
std::deque
std::vector
for (int i = 0; i < nums.size(); ++i) {
// 移除超出窗口的元素
while (!dq.empty() && dq.front() <= i - k) {
dq.pop_front();
}
// 保持单调性:移除比当前元素小的元素
while (!dq.empty() && nums[dq.back()] < nums[i]) {
dq.pop_back();
}
dq.push_back(i);
// 记录结果
if (i >= k – 1) {
result.push_back(nums[dq.front()]);
}
}
return result;
}
};
6.6 前缀树(Trie)
#include
#include
#include
class TrieNode {
public:
std::vector
bool isEndOfWord;
TrieNode() : children(26, nullptr), isEndOfWord(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(const std::string& word) {
TrieNode* node = root;
for (char c : word) {
int index = c – ‘a’;
if (!node->children[index]) {
node->children[index] = new TrieNode();
}
node = node->children[index];
}
node->isEndOfWord = true;
}
bool search(const std::string& word) {
TrieNode* node = root;
for (char c : word) {
int index = c – ‘a’;
if (!node->children[index]) return false;
node = node->children[index];
}
return node->isEndOfWord;
}
bool startsWith(const std::string& prefix) {
TrieNode* node = root;
for (char c : prefix) {
int index = c – ‘a’;
if (!node->children[index]) return false;
node = node->children[index];
}
return true;
}
};
七、实战应用:综合案例分析
7.1 案例1:任务调度器
问题
:给定任务数组和冷却时间n,求最少完成时间。
#include
#include
#include
#include
class TaskScheduler {
public:
int leastInterval(const std::vector
std::vector
for (char task : tasks) {
freq[task – ‘A’]++;
}
// 找出最大频率
int maxFreq = *std::max_element(freq.begin(), freq.end());
// 计算有多少个任务具有最大频率
int countMaxFreq = std::count(freq.begin(), freq.end(), maxFreq);
// 计算最少时间
int partCount = maxFreq – 1;
int partLength = n + 1;
int emptySlots = partCount * partLength – countMaxFreq;
int availableTasks = tasks.size() – maxFreq * countMaxFreq;
int idleTime = std::max(0, emptySlots – availableTasks);
return tasks.size() + idleTime;
}
};
7.2 案例2:俄罗斯套娃信封问题
问题
:给定信封宽高,求最多能套多少个信封。
#include
#include
#include
class RussianDollEnvelopes {
public:
int maxEnvelopes(std::vector
if (envelopes.empty()) return 0;
// 按宽度升序,高度降序排序
std::sort(envelopes.begin(), envelopes.end(),
[](const std::vector
return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
});
// 提取高度,转化为最长递增子序列问题
std::vector
for (const auto& env : envelopes) {
heights.push_back(env[1]);
}
return lengthOfLIS(heights);
}
private:
int lengthOfLIS(const std::vector
std::vector
for (int num : nums) {
auto it = std::lower_bound(tails.begin(), tails.end(), num);
if (it == tails.end()) {
tails.push_back(num);
} else {
*it = num;
}
}
return tails.size();
}
};
7.3 案例3:数据流中的中位数
问题
:动态维护数据流的中位数。
#include
#include
#include
class MedianFinder {
private:
// 大顶堆,存储较小的一半
std::priority_queue
// 小顶堆,存储较大的一半
std::priority_queue
public:
void addNum(int num) {
// 先加入大顶堆
maxHeap.push(num);
// 平衡:大顶堆的最大值不能大于小顶堆的最小值
minHeap.push(maxHeap.top());
maxHeap.pop();
// 保持大小平衡
if (maxHeap.size() < minHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
double findMedian() {
if (maxHeap.size() > minHeap.size()) {
return maxHeap.top();
}
return (maxHeap.top() + minHeap.top()) / 2.0;
}
};
7.4 案例4:接雨水
问题
:计算能接多少雨水。
#include
#include
#include
class TrappingRainWater {
public:
int trap(const std::vector
if (height.empty()) return 0;
int left = 0, right = height.size() – 1;
int leftMax = 0, rightMax = 0;
int water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax – height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax – height[right];
}
right–;
}
}
return water;
}
};
7.5 案例5:最大矩形面积
问题
:在0-1矩阵中找到最大的全1矩形。
#include
#include
#include
#include
class MaximalRectangle {
public:
int maximalRectangle(const std::vector
if (matrix.empty() || matrix[0].empty()) return 0;
int rows = matrix.size();
int cols = matrix[0].size();
std::vector
int maxArea = 0;
for (int i = 0; i < rows; ++i) {
// 更新高度
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
// 单调栈计算最大矩形
std::stack
for (int j = 0; j <= cols; ++j) {
while (!st.empty() && heights[st.top()] > heights[j]) {
int h = heights[st.top()];
st.pop();
int w = st.empty() ? j : j – st.top() – 1;
maxArea = std::max(maxArea, h * w);
}
st.push(j);
}
}
return maxArea;
}
};
八、高级主题:高级数据结构与算法
8.1 线段树
线段树用于区间查询和更新。
#include
#include
#include
class SegmentTree {
private:
std::vector
std::vector
int n;
void build(int node, int start, int end) {
if (start == end) {
tree[node] = nums[start];
return;
}
int mid = (start + end) / 2;
build(2 * node + 1, start, mid);
build(2 * node + 2, mid + 1, end);
tree[node] = tree[2 * node + 1] + tree[2 * node + 2];
}
int query(int node, int start, int end, int l, int r) {
if (r < start || end < l) return 0; // 完全在范围外
if (l <= start && end <= r) return tree[node]; // 完全在范围内
int mid = (start + end) / 2;
int leftSum = query(2 * node + 1, start, mid, l, r);
int rightSum = query(2 * node + 2, mid + 1, end, l, r);
return leftSum + rightSum;
}
void update(int node, int start, int end, int idx, int val) {
if (start == end) {
tree[node] = val;
return;
}
int mid = (start + end) / 2;
if (idx <= mid) {
update(2 * node + 1, start, mid, idx, val);
} else {
update(2 * node + 2, mid + 1, end, idx, val);
}
tree[node] = tree[2 * node + 1] + tree[2 * node + 2];
}
public:
SegmentTree(const std::vector
nums = data;
n = data.size();
tree.resize(4 * n);
build(0, 0, n – 1);
}
int query(int left, int right) {
return query(0, 0, n – 1, left, right);
}
void update(int idx, int val) {
update(0, 0, n – 1, idx, val);
nums[idx] = val;
}
};
8.2 树状数组(Fenwick Tree)
#include
#include
class FenwickTree {
private:
std::vector
int n;
public:
FenwickTree(int size) : n(size), bit(size + 1, 0) {}
// 单点更新:index位置增加delta
void update(int index, int delta) {
index++; // 转换为1-based
while (index <= n) {
bit[index] += delta;
index += index & (-index);
}
}
// 前缀和查询:[0, index]
int query(int index) {
index++;
int sum = 0;
while (index > 0) {
sum += bit[index];
index -= index & (-index);
}
return sum;
}
// 区间和查询:[left, right]
int rangeQuery(int left, int right) {
return query(right) – query(left – 1);
}
};
8.3 平衡二叉搜索树(AVL树)
#include
#include
struct AVLNode {
int key;
int height;
AVLNode* left;
AVLNode* right;
AVLNode(int k) : key(k), height(1), left(nullptr), right(nullptr) {}
};
class AVLTree {
private:
AVLNode* root;
int height(AVLNode* node) {
return node ? node->height : 0;
}
int getBalance(AVLNode* node) {
return node ? height(node->left) – height(node->right) : 0;
}
void updateHeight(AVLNode* node) {
node->height = 1 + std::max(height(node->left), height(node->right));
}
AVLNode* rightRotate(AVLNode* y) {
AVLNode* x = y->left;
AVLNode* T2 = x->right;
x->right = y;
y->left = T2;
updateHeight(y);
updateHeight(x);
return x;
}
AVLNode* leftRotate(AVLNode* x) {
AVLNode* y = x->right;
AVLNode* T2 = y->left;
y->left = x;
x->right = T2;
updateHeight(x);
updateHeight(y);
return y;
}
AVLNode* insert(AVLNode* node, int key) {
if (!node) return new AVLNode(key);
if (key < node->key) {
node->left = insert(node->left, key);
} else if (key > node->key) {
node->right = insert(node->right, key);
} else {
return node; // 重复值
}
updateHeight(node);
int balance = getBalance(node);
// Left Left Case
if (balance > 1 && key < node->left->key) {
return rightRotate(node);
}
// Right Right Case
if (balance < -1 && key > node->right->key) {
return leftRotate(node);
}
// Left Right Case
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
public:
AVLTree() : root(nullptr) {}
void insert(int key) {
root = insert(root, key);
}
bool search(int key) {
AVLNode* current = root;
while (current) {
if (key == current->key) return true;
if (key < current->key) current = current->left;
else current = current->right;
}
return false;
}
};
8.4 字符串匹配算法
KMP算法
:
#include
#include
#include
class KMP {
private:
std::vector
int n = pattern.size();
std::vector
int len = 0;
int i = 1;
while (i < n) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
public:
int search(const std::string& text, const std::string& pattern) {
int m = pattern.size();
int n = text.size();
if (m == 0) return 0;
std::vector
int i = 0; // text索引
int j = 0; // pattern索引
while (i < n) {
if (pattern[j] == text[i]) {
i++;
j++;
}
if (j == m) {
return i - j; // 找到匹配
// 若要找所有匹配:j = lps[j-1];
} else if (i < n && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return -1;
}
};
Boyer-Moore算法
:
#include
#include
#include
#include
class BoyerMoore {
private:
std::unordered_map
void preprocessBadChar(const std::string& pattern) {
int m = pattern.size();
for (int i = 0; i < m; ++i) {
badCharShift[pattern[i]] = m - 1 - i;
}
}
public:
int search(const std::string& text, const std::string& pattern) {
int m = pattern.size();
int n = text.size();
preprocessBadChar(pattern);
int i = 0; // text中的起始位置
while (i <= n - m) {
int j = m - 1;
while (j >= 0 && pattern[j] == text[i + j]) {
j–;
}
if (j < 0) {
return i; // 匹配成功
} else {
// 根据坏字符规则移动
char badChar = text[i + j];
if (badCharShift.find(badChar) != badCharShift.end()) {
i += badCharShift[badChar];
} else {
i += m;
}
}
}
return -1;
}
};
8.5 最大流算法(Edmonds-Karp)
#include
#include
#include
#include
#include
class MaxFlow {
private:
std::vector
std::vector
int n;
public:
MaxFlow(int vertices) : n(vertices) {
capacity.resize(n, std::vector
adj.resize(n);
}
void addEdge(int u, int v, int cap) {
capacity[u][v] = cap;
adj[u].push_back(v);
adj[v].push_back(u); // 反向边
}
int edmondsKarp(int source, int sink) {
int flow = 0;
std::vector
while (true) {
// BFS找增广路径
std::fill(parent.begin(), parent.end(), -1);
std::queue
q.push(source);
parent[source] = source;
while (!q.empty() && parent[sink] == -1) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (parent[v] == -1 && capacity[u][v] > 0) {
parent[v] = u;
q.push(v);
}
}
}
if (parent[sink] == -1) break; // 无增广路径
// 找路径上的最小容量
int pathFlow = INT_MAX;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = std::min(pathFlow, capacity[u][v]);
}
// 更新残余网络
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
capacity[u][v] -= pathFlow;
capacity[v][u] += pathFlow;
}
flow += pathFlow;
}
return flow;
}
};
九、算法优化与调试技巧
9.1 时间复杂度优化策略
降低复杂度级别
:O(n²) → O(n log n) → O(n) → O(log n)
空间换时间
:使用哈希表、预计算等
避免重复计算
:记忆化、动态规划
提前终止
:剪枝、break/continue
数据结构优化
:选择合适的数据结构
9.2 空间复杂度优化策略
原地操作
:修改输入数组而非创建新数组
滚动数组
:只保留必要的历史信息
位运算压缩
:用位表示状态
延迟计算
:按需计算而非预计算
9.3 调试技巧
// 1. 打印中间状态
template
void printVector(const std::vector
if (!name.empty()) std::cout << name << ": ";
for (const auto& val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
}
// 2. 验证算法正确性
void testAlgorithm() {
// 测试用例1:正常情况
std::vector
// 验证结果
// 测试用例2:边界情况
std::vector
std::vector
// 测试用例3:重复元素
std::vector
// 测试用例4:负数
std::vector
}
// 3. 性能测试
#include
void benchmark() {
auto start = std::chrono::high_resolution_clock::now();
// 执行算法
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast
std::cout << "Time: " << duration.count() << " μs" << std::1;
}
9.4 常见错误与陷阱
整数溢出
:使用long long或取模运算
数组越界
:注意边界条件
未初始化变量
:确保变量初始化
无限循环
:确保循环有终止条件
内存泄漏
:及时释放动态分配的内存
浮点数精度
:避免直接比较浮点数
引用传递vs值传递
:注意参数传递方式
9.5 C++特定优化技巧
// 1. 使用reserve避免重复分配
std::vector
result.reserve(n); // 预分配空间
// 2. 使用emplace_back代替push_back
std::vector
vec.emplace_back(1, 2); // 避免临时对象
// 3. 移动语义
std::vector
std::vector
// …
return temp; // RVO/NRVO优化
}
// 4. 使用数组代替vector(固定大小)
int arr[100]; // 栈上分配,更快
// 5. 使用string_view避免拷贝
#include
void process(std::string_view sv) {
// 不拷贝字符串
}
// 6. 编译器优化提示
#pragma GCC optimize(“O3”)
#pragma GCC target(“avx2”)
十、总结与进阶建议
10.1 算法学习路径
基础阶段
:排序、查找、递归、简单DP
中级阶段
:图算法、高级DP、贪心、数据结构
高级阶段
:网络流、计算几何、字符串算法、高级数据结构
实战阶段
:参加竞赛、刷题、项目应用
10.2 推荐练习平台
LeetCode
:面试导向,分类清晰
Codeforces
:竞赛导向,难度较高
AtCoder
:日本平台,题目质量高
牛客网
:国内平台,企业真题
10.3 持续学习建议
定期复习
:温故而知新
总结模板
:建立自己的代码库
阅读源码
:学习STL实现
参与社区
:讨论交流,共同进步
应用实践
:将算法应用到实际项目中
10.4 性能分析工具
// 使用perf工具(Linux)
// perf record ./your_program
// perf report
// 使用gprof
// g++ -pg your_program.cpp
// ./your_program
// gprof your_program gmon.out
// 使用Valgrind检测内存泄漏
// valgrind –leak-check=full ./your_program
10.5 算法竞赛技巧
快速模板
:准备常用算法模板
时间分配
:先易后难,确保得分
调试技巧
:使用对拍验证
心理素质
:保持冷静,仔细审题
结语
C++算法设计是一门艺术,需要理论与实践相结合。通过系统学习基础概念,掌握高级技巧,并在实际项目中不断应用,你将能够编写出高效、优雅的代码。记住,算法思维的核心是
分解问题
、
抽象模式
和
优化实现
。
持续练习,保持好奇心,你一定能成为算法高手!