Graph题目总结【不定期更新】

Find minimal ops to convert one str to another

Description Given two alphabet strings str1 and str2. You can change the characters in str1 to any alphabet characters in order to transform str1 to str2. One restriction is, in each operation, you should change all the same characters simultaneously. What's more, you may use another special character * if necessary, which means during each operations, you may change the alphabet characters to *, or change each * to a specific character. We want to know the minimum operation times. If impossible, return -1. Template
int MinOpTimes(string str1, string str2) { //...
};
Examples
 
Example 1:
str1: accs, str2: eeec
operation 1: change 'a'->'e'; // str1: eccs operation 2: change 'c'->'e'; // str1: eees operation 3: change 's'->'c'; // str1: eeec return 3;
Example 2:
str1: accs, str2: efec return -1;
Example 3:
str1: abb , str2: baa
operation 1: change 'a'->'*'; // str1: *bb operation 2: change 'b'->'a'; // str1: *aa
operation 3: change '*'->'b'; // str1: baa return 3;
 
accs -> eeec: 3

accs -> efec: -1

 abb -> baa: 3

 可以看到如果想要convert成功所有的node的out degree要小于等于1才可以。答案是计算edges+cycle的数量。

Alien Dictionary

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:

Input: [ "wrt", "wrf", "er", "ett", "rftt" ] Output: "wertf"

Example 2:

Input: [ "z", "x" ] Output: "zx"

Example 3:

Input: [ "z", "x", "z" ] Output: ""  Explanation: The order is invalid, so return "".

Note:

  1. You may assume all letters are in lowercase.

  2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.

  3. If the order is invalid, return an empty string.

  4. There may be multiple valid order of letters, return any one of them is fine.

Topological sort: similar with course schedule series

e.g. [ "wrt", "wrf", "er", "ett", "rftt" ]

1. wrt -> wrf: t -> f

2. wrt -> er:  w -> e

3. er -> ett: r -> t

4. ett -> rftt: e -> r

e.g. [ "z", "x", "z" ] : 有环 -> invalid

猜你喜欢

转载自www.cnblogs.com/goldenticket/p/12221303.html