【CodeForces 939D --- Love Rescue】并查集 || dfs

【CodeForces 939D --- Love Rescue】并查集 || dfs

题目来源:点击进入【CodeForces 939D — Love Rescue】

Description

Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn’t want to see him and Tolya is seating at his room and crying at her photos all day long.

This story could be very sad but fairy godmother (Tolya’s grandmother) decided to help them and restore their relationship. She secretly took Tolya’s t-shirt and Valya’s pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya’s grandmother should spend to rescue love of Tolya and Valya.

More formally, letterings on Tolya’s t-shirt and Valya’s pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c1, c2) (where c1 and c2 are some lowercase English letters), which can arbitrary number of times transform a single letter c1 to c2 and vise-versa on both Tolya’s t-shirt and Valya’s pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the length of the letterings.

The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya’s pullover.

The third line contains the lettering on Tolya’s t-shirt in the same format.

扫描二维码关注公众号,回复: 9963664 查看本文章

Output

In the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya.

In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya’s grandmother should buy. Spells and letters in spells can be printed in any order.

If there are many optimal answers, output any.

Sample Input

3
abb
dad

Sample Output

2
a d
b a

解题思路

AC代码(C++):

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
const int MAXN = 30;
int pre[MAXN];
pair<char,char> p[MAXN];

void init()
{
    for(int i=0;i<26;i++)
        pre[i]=i;
}

int _find(int x)
{
    if(x==pre[x]) return x;
    return pre[x]=_find(pre[x]);
}

void unite(int x,int y)
{
    x=_find(x);
    y=_find(y);
    if(x!=y) pre[x]=y;
}

int main()
{
    SIS;
    int n,ans=0;
    string s,t;
    init();
    cin >> n >> s >> t;
    for(int i=0;i<n;i++)
    {
        int u=s[i]-'a',v=t[i]-'a';
        if(_find(u)!=_find(v))
        {
            p[ans++]=make_pair(s[i],t[i]);
            unite(u,v);
        }
    }
    cout << ans << endl;
    for(int i=0;i<ans;i++)
        cout << p[i].first << ' ' << p[i].second << endl;
    return 0;
}

AC代码(python):

from sys import stdin


def dfs(x, res):
    if vis[x]:
        return
    vis[x] = True
    res.append(x)
    for y in g[x]:
        dfs(y, res)


n = int(stdin.readline())
s = stdin.readline()
t = stdin.readline()
vis = [False] * 26
g = [set() for _ in range(26)]
for i in range(n):
    if s[i] == t[i]:
        continue
    x = ord(s[i]) - ord('a')
    y = ord(t[i]) - ord('a')
    g[x].add(y)
    g[y].add(x)
ans = []
for x in range(26):
    if not vis[x]:
        res = []
        dfs(x, res)
        for i in range(1, len(res)):
            x = chr(res[0] + ord('a'))
            y = chr(res[i] + ord('a'))
            ans.append((x, y))
print(len(ans))
for i in ans:
    print(*i)

AC代码(java):

import java.util.Scanner;

public class Main {

    static int[] pre;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pre = new int[26];
        int n=sc.nextInt(), res=0;
        String s = sc.next();
        String t = sc.next();
        for(int i=0;i<26;i++) {
            pre[i] = i;
        }
        String ans = "";
        for(int i=0;i<n;i++) {
            int x = s.charAt(i) - 'a';
            int y = t.charAt(i) - 'a';
            if(find(x) != find(y)) {
                res++;
                pre[find(x)] = find(y);
                ans += s.charAt(i) + " " + t.charAt(i) + "\n";
            }
        }
        System.out.println(res);
        System.out.print(ans);
    }

    public static int find(int x) {
        if(pre[x]==x) return x;
        return pre[x]=find(pre[x]);
    }
}

AC代码(go):

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

func solve(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n int
	var s, t []byte
	Fscan(in, &n, &s, &t)
	pre := make([]byte, 'z'+1)
	for i := range pre {
		pre[i] = byte(i)
	}
	var find func(byte) byte
	find = func(x byte) byte {
		if pre[x] != x {
			pre[x] = find(pre[x])
		}
		return pre[x]
	}
	ans := [][2]byte{}
	for i, ch := range s {
		if find(ch) != find(t[i]) {
			pre[find(ch)] = find(t[i])
			ans = append(ans, [2]byte{ch, t[i]})
		}
	}
	Fprintln(out, len(ans))
	for _, x := range ans {
		Fprintf(out, "%c %c\n", x[0], x[1])
	}
}

func main() {
	solve(os.Stdin, os.Stdout)
}
发布了476 篇原创文章 · 获赞 152 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_41879343/article/details/104536301