Coming_soon's blog

By Coming_soon, 9 years ago, In English

Hello.I am trying to solve the following problem, i found a code ,where it used dfs(),but i cannot understand its logic. can anyone tell me,what is the dfs() logic?. i know dfs().

problem:http://codeforces.com/contest/278/problem/B

code:http://codepad.org/gcvW73mV

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Okay so the basic observation you have to make in this problem, is that you have in total at most 30 strings of 20 characters. This would make in total worst-case of about 570 combinations of 2-letters in these strings, and there are in total 676 2-letter combinations. So the answer is always 1 or 2 letters long.

So let's move on to the "DFS" solution you linked to. What this DFS does is simple. It has three parameters:

int k — this is the current length of the string formed

int d — this is the goal length of the string formed

string ss — this is the string formed itself

Then, on each next call the recursion increases k and adds a letter until you get a d-letters-long string. Then this string is checked to be an answer. Since the recursion first tries to add 'a', then 'b', then 'c' and so on, the resulting d-letters-long strings are generated in lexicographical order.

So this solution boils down to fixing a length, generating all strings of that length and picking the smallest lexicographical string that fits the answer. If no strings fits it, you just increase the length and generate all strings again. Because of the small amount of strings you have on the input, the maximum length you search for is actually 2.