1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
// 基本 DFS
void dfs(int start, const vector<vector<int>>& adj)
{
int n = adj.size();
vector<bool> visited(n, false);
stack<int> s;
s.push(start);
visited[start] = true;
while (!s.empty())
{
int u = s.top();
s.pop();
cout << u << " ";
for (auto it = adj[u].rbegin(); it != adj[u].rend(); ++it)
{
int v = *it;
if (!visited[v])
{
visited[v] = true;
s.push(v);
}
}
}
cout << endl;
}
// 括号匹配
bool is_valid_parentheses(const string& s)
{
stack<char> stk;
unordered_map<char, char> mapping = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : s)
{
if (mapping.count(c))
{
char top_element = stk.empty() ? '#' : stk.top();
stk.pop();
if (top_element != mapping[c])
{
return false;
}
}
else
{
stk.push(c);
}
}
return stk.empty();
}
// 每日温度
vector<int> daily_temperatures(vector<int>& temperatures)
{
int n = temperatures.size();
vector<int> result(n, 0);
stack<int> stk;
for (int i = n - 1; i >= 0; i--)
{
while (!stk.empty() && temperatures[stk.top()] <= temperatures[i])
{
stk.pop();
}
result[i] = stk.empty() ? 0 : stk.top() - i;
stk.push(i);
}
return result;
}
// 表达式求值
int evaluate_postfix(const vector<string>& tokens)
{
stack<int> s;
for (const string& token : tokens)
{
if (token == "+" || token == "-" || token == "*" || token == "/")
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
if (token == "+" || token == "-") s.push(token == "+" ? a + b : a - b);
else s.push(token == "*" ? a * b : a / b);
}
else
{
s.push(stoi(token));
}
}
return s.top();
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 测试 DFS
int n = 6;
vector<vector<int>> adj(n);
adj[0] = {1, 2};
adj[1] = {0, 3, 4};
adj[2] = {0, 5};
adj[3] = {1};
adj[4] = {1};
adj[5] = {2};
cout << "DFS 遍历: ";
dfs(0, adj);
// 测试括号匹配
string s = "{[]()}";
cout << "括号匹配: " << (is_valid_parentheses(s) ? "有效" : "无效") << endl;
// 测试每日温度
vector<int> temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
vector<int> result = daily_temperatures(temperatures);
cout << "每日温度: ";
for (int x : result)
{
cout << x << " ";
}
cout << endl;
// 测试表达式求值
vector<string> tokens = {"2", "1", "+", "3", "*"};
cout << "表达式求值: " << evaluate_postfix(tokens) << endl; // (2+1)*3=9
return 0;
}
|