6.9每日一题题解

解方程

涉及知识点:

  • 并查集

solution:

  • 一个并查集的模板题
  • 只需要用map给字符串编号即可

std:

#include <bits/stdc++.h>

using namespace std;

const int N = 20010;

int p[N];

map<string,int> mp;

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

int main()
{
    int n,m;
    cin >> n >> m;
    for (int i = 1 ; i <= n ; i ++ )
    {
        string s;
        cin >> s;
        p[i] = i;
        mp[s] = i;
    }
    while(m -- )
    {
        int type;
        string s1,s2;
        cin >> type >> s1 >> s2;
        int x = mp[s1];
        int y = mp[s2];
        if(type == 1)
        {
            p[find(x)] = find(y);
        }
        else if(type == 2)
        {
            if(find(x) == find(y))
            {
                puts("1");
            }
            else
            {
                puts("0");
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QFNU-ACM/p/13068039.html