A - 4302. 元素分类

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
    ll n, x, sum = 0;
    cin >> n;

    for (int i = 1; i <= n; i++)
    {
        cin >> x;
        sum += abs(x);
    }

    cout << sum;
    return 0;
}

B - 4303. 链表

Code

#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;

int n;
unordered_map<string,string> m;
string s1, s2;

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        bool flag = false;
        cin >> s1 >> s2;
        
        for (auto &item : m)
            if (item.y == s1)
            {
                item.y = s2;
                flag = true;
                break;
            }
        
        if (!flag)  m[s1] = s2;
    }    

    cout << m.size() << endl;
    for (auto item : m)
        cout << item.x << ' ' << item.y << endl;
    
    return 0;
}

C - 4304. 字符串归类(并查集)

题目描述

avatar

解题思路

对于每个字符串中的字符用id数组来比较
如果之前没出现过,就赋值为i(第几个字符串)
如果出现过,就合并。(合并之后仍然要遍历这个字符串,目的是为了完善id数组)

Code

#include <bits/stdc++.h>
using namespace std;
const int N = 200020;

int n, p[N], id[30];
string str;

int find(int x)
{
    if (p[x] != x)  p[x] = find(p[x]);
    return p[x];
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++) p[i] = i;
    
    int res = n;
    for (int i = 1; i <= n; i++)
    {
        cin >> str;
        for (auto x : str)
        {
            if (id[x - 'a'])
            {
                if (find(i) != find(id[x - 'a']))
                {
                    p[find(i)] = find(id[x - 'a']);
                    res--;
                }
            }
            else id[x - 'a'] = i;
        }
    }
    
    cout << res;
    return 0;
}
上一篇 下一篇