1、数列分段
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, a[N];
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
int res = 1;
int val = a[0];
for (int i = 1; i < n; i++)
if (a[i] == val) continue;
else val = a[i], res++;
cout << res << endl;
return 0;
}
2、日期计算
#include <iostream>
#include <algorithm>
using namespace std;
const int month[13] = {0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
int is_leap(int y) {
if (y % 4 == 0 && y % 100 || y % 400 == 0) return 1;
return 0;
}
int get_month_day(int y, int m) {
if (m == 2) return month[m] + is_leap(y);
return month[m];
}
int main() {
int y, s; cin >> y >> s;
int m = 1, d = 1; s--;
while (s--)
if (++d > get_month_day(y, m)) {
d = 1, m++;
if (m > 12)
m = 1, y++;
}
cout << m << endl << d << endl;
return 0;
}
3、模板生成系统
#include <iostream>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <vector>
using namespace std;
int n, m;
vector<string> strs;
unordered_map<string, string> vars;
int main() {
cin >> n >> m; getchar();
while (n--) {
string str; getline(cin, str);
strs.push_back(str);
}
while (m--) {
string key, value; cin >> key;
char c;
while (c = getchar(), c != '\"');
while (c = getchar(), c != '\"') value += c;
vars[key] = value;
}
for (auto &str: strs) {
for (int i = 0; i < str.size();)
if (i + 1 < str.size() && str[i] == '{' && str[i + 1] == '{') {
int j = i + 3;
string key;
while (str[j] != ' ' || str[j + 1] != '}' || str[j + 2] != '}')
key += str[j++];
cout << vars[key];
i = j + 3;
} else cout << str[i++];
puts("");
}
return 0;
}
4、高速公路(强连通分量)
如果图中 A A A 能够走到 B B B 并且 B B B 也能够走到 A A A,那么两点一定在同一个强连通分量中。所以可以先求出图中所有的强连通分量,对于每一个强连通分量,如果内部存在 n n n 个点,那么这个强连通分量中可以相互到达的点的数量为 C n 2 C_n^2 Cn2。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010, M = 100010;
int n, m;
int h[N], e[M], ne[M], idx;
int dfn[N], low[N];
int stk[N], top, ts;
bool in_stk[N];
int ans;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void tarjan(int u) {
dfn[u] = low[u] = ++ts;
stk[++top] = u, in_stk[u] = true;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (!dfn[j]) {
tarjan(j);
low[u] = min(low[u], low[j]);
} else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
}
if (dfn[u] == low[u]) {
int y, cnt = 0;
do {
y = stk[top--];
in_stk[y] = false;
cnt++;
} while (y != u);
ans += cnt * (cnt - 1) / 2;
}
}
int main() {
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m--) {
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
for (int i = 1; i <= n; i++)
if (!dfn[i])
tarjan(i);
printf("%d\n", ans);
return 0;
}