Title Link: Http://codeforces.com/contest/510/problem/C
The main idea: to construct an alphabet so that your alphabet can satisfy the input is sorted by dictionary order.
Recursive build: Vertically cut down and connect the first x letters of each name from top to bottom to create a diagram. Then the topology is sorted.
The reason to sort the topology, because to judge in the x-1 there is a-->b in X has b-->a, so that a ring formed. In this way, the alphabet cannot be constructed.
"Lessons Learned": Two arrays are opened in a recursive map function to record the first occurrence and last occurrence of the letter. The result is re on 12. Try not to open an array in a recursive function in the future.
1#include <cstdio>2#include <algorithm>3#include <bitset>4#include <Set>5#include <vector>6#include <iterator>7#include <cstring>8#include <map>9#include <cctype>Ten#include <iostream> One#include <string> A#include <stdexcept> - using namespacestd; - the intN; - stringnames[111]; - BOOLHasans =true; -vector<int> g[ -]; + intc[ -],topo[ -],t; - + voidSolveintLintRintx) { A if(L>=R)return; at if(!hasans)return; - for(inti=l;i<=r;i++){ - if(x>=names[i].size ()) { -Hasans =false; - return; - } in intj = i+1; - for(; j<=r;j++){ to if(names[i][x]==Names[j][x]) { + Continue; -}Else { the Break; * } $ }Panax Notoginseng while(Names[i].size ()-1<x+1&&i<j-1) i++; -Solve (i,j-1, x+1); thei = j1; + } A the for(inti=l;i<r;i++) { + if(names[i][x]==names[i+1][X])Continue; -g[names[i][x]-'a'].push_back (names[i+1][x]-'a'); $ } $ } - - BOOLDfsintu) { theC[u] =-1; - for(intI=0; I<g[u].size (); i++){Wuyi intv =G[u][i]; the if(v<0)Continue; - if(c[v]<0)return false; Wu Else if(!c[v] &&!dfs (v))return false; - } AboutC[u] =1; TOPO[--T] =u; $ return true; - } - - BOOLToposort () { At = -; +Memset (c,0,sizeof(c)); the for(intu= -; u>=0; u--)if(!C[u]) - if(!dfs (U))return false; $ return true; the } the the intMain () { theCIN >>N; - for(intI=0; i<n;i++) Cin >>Names[i]; inSolve0, N-1,0); the if( !Hasans) { thePuts"Impossible"); About return 0; the } the BOOLHasans =Toposort (); the if( !Hasans) { +Puts"Impossible"); - return 0; the }Bayi for(intI=0;i< -; i++){ thePutchar ('a'+topo[i]); the } -Puts""); - the return 0; the}
[CF #290-c] Fox and Names (topological sort)