元素分类
将所有正数分到一类,负数分到一类,和最大值就是每个数绝对值求和
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
int a[N];
int main()
{
scanf("%d", &n);
int res = 0;
for (int i = 0; i < n; i ++ )
{
int x;
scanf("%d", &x);
res += abs(x);
}
cout << res << endl;
return 0;
}
链表
因为链表出现的次数是有序的,所以不需要处理一个链表之间元素的关系,用一个map存每个链表的前驱。如果我们存后继,当我们用后继去更新之后的结点时无法找到前驱,因此我们每个链表存储前驱结点
#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int N = 1010;
map<string, string> m;
int main()
{
int q;
scanf("%d", &q);
for (int i = 0; i < q; i ++ )
{
string a, b;
cin >> a >> b;
if (!m.count(a))
{
m[b] = a;
}
else
{
string t = m[a];
m.erase(a);
m[b] = t;
}
}
cout << m.size() << endl;
for (auto t : m)
cout << t.second << ' ' << t.first << endl;
return 0;
}
字符串归类
维护每个字母第一次出现的字符串编号,每次合并新字符串和
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e5 + 5;
int n, p[N], a[26];
string s;
int find(int x) // 并查集
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void merge(int x, int y) {
p[find(x)] = find(y);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 1; i <= n; i++) {
cin >> s;
for (char c: s) {
int v = c - 'a';
if (!a[v]) a[v] = i;
else merge(a[v], i);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) if (find(i) == i) ans++;
cout << ans;
return 0;
}