1、门禁系统
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n;
int a[N], cnt[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i ++ ) {
int x; cin >> x;
cnt[x] ++ ;
cout << cnt[x] << " ";
}
puts("");
return 0;
}
2、Z字形扫描
对原图补充两个矩形后,顺时针翻转
4
5
o
45^o
45o 后可得下图:
观察右图中规律:
- 每行元素的行列之和都是固定的,记为 i i i;
- 如果 i i i 为偶数,就从左到右遍历,记行号为 j j j,那么行号就从 i − 1 → 1 i - 1 \rightarrow 1 i−1→1,列号为 i − j i - j i−j;
- 如果 i i i 为奇数,从右到左遍历,行号为 j j j,行号从 1 → i − 1 1 \rightarrow i - 1 1→i−1,列号为 i − j i - j i−j。
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 510;
int n, q[N][N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> q[i][j];
for (int i = 2; i <= n + n; i++)
if (i % 2) {
for (int j = 1; j <= i - 1; j++)
if (j >= 1 && j <= n && i - j >= 1 && i - j <= n)
cout << q[j][i - j] << ' ';
} else {
for (int j = i - 1; j; j--)
if (j >= 1 && j <= n && i - j >= 1 && i - j <= n)
cout << q[j][i - j] << ' ';
}
return 0;
}
3、集合竞价
这个题有一个小细节:在输入指令cancel i
的时候,除了要标记删除第
i
i
i 条指令插入的数据,还要将这条
c
a
n
c
e
l
cancel
cancel 指令一起标记删除,并且一起加入结构体数组
s
t
st
st 中,不能因为这条指令不会插入数据而不插入结构体
s
t
st
st 中,如果不插入,后面又执行
c
a
n
c
e
l
cancel
cancel 删除第
i
i
i 条指令的时候,
i
i
i 会出错。
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 5010;
struct Stock {
double p;
int s, type;
} st[N];
int main() {
string str;
int n = 1;
while (cin >> str)
if (str == "buy") {
cin >> st[n].p >> st[n].s;
st[n++].type = 1;
} else if (str == "sell") {
cin >> st[n].p >> st[n].s;
st[n++].type = 2;
} else {
int x; cin >> x;
st[x].type = 0;1
st[n++].type = 0; // 也要加入!
}
LL ress = 0;
double resp = 0;
for (int i = 1; i <= n; i++)
if (st[i].type) {
LL s1 = 0, s2 = 0;
double p = st[i].p;
for (int j = 1; j <= n; j++)
if (st[j].type) {
if (st[j].type == 1 && st[j].p >= p) s1 += st[j].s;
else if (st[j].type == 2 && st[j].p <= p) s2 += st[j].s;
}
LL t = min(s1, s2);
if (t > ress || t == ress && p > resp) resp = p, ress = t;
}
printf("%.2lf %lld\n", resp, ress);
return 0;
}
4、最优灌溉
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int p[N];
struct Edge {
int a, b, c;
bool operator<(const Edge &w) const {
return c < w.c;
}
} e[N];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 0; i < m; i++) {
int a, b, c; scanf("%d%d%d", &a, &b, &c);
e[i] = {a, b, c};
}
sort(e, e + m);
int res = 0;
for (int i = 0; i < m; i++) {
int a = e[i].a, b = e[i].b, c = e[i].c;
if (find(a) != find(b)) {
res += c;
p[find(a)] = find(b);
}
}
printf("%d\n", res);
return 0;
}