[UVA] 200 - Rare Order
Rare Order
Rare Order |
A rare book collector recently discovered a book written in an unfamiliar language that used the same characters as the English language. The book contained a short index, but the ordering of the items in the index was different from what one would expect if the characters were ordered the same way as in the English alphabet. The collector tried to use the index to determine the ordering of characters (i.e., the collating sequence) of the strange alphabet, then gave up with frustration at the tedium of the task.
You are to write a program to complete the collector's work. In particular, your program will take a set of strings that has been sorted according to a particular collating sequence and determine what that sequence is.
Input
The input consists of an ordered list of strings of uppercase letters, one string per line. Each string contains at most 20 characters. The end of the list is signalled by a line with the single character `#'. Not all letters are necessarily used, but the list will imply a complete ordering among those letters that are used.
Output
Your output should be a single line containing uppercase letters in the order that specifies the collating sequence used to produce the input data file.
Sample Input
XWY ZX ZXY ZXW YWWX #
Sample Output
XZYW
作法 : 拓樸排序
#include<stdio.h>
#include<string.h>
int Map[26][26], App[26], Used[26];
void compare(const char *A, const char *B) {
while(*A && *B && *A == *B) {
A++;
B++;
}
if(*A && *B) {
char cA, cB;
cA = *A - 'A', cB = *B - 'A';
Map[cA][cB] = 1;
App[cA] = 1, App[cB] = 1;
}
}
int main() {
int n = 0, i, j;
char *pre = new char[255];
char *cur = new char[255];
memset(Map, 0, sizeof(Map));
memset(App, 0, sizeof(App));
memset(Used, 0, sizeof(Used));
scanf("%s", pre), n++;
while(scanf("%s", cur) == 1) {
if(cur[0] == '#') break;
compare(pre, cur);
char *tmp;
tmp = pre, pre = cur, cur = tmp;
n++;
}
while(1) {
for(i = 0; i < 26; i++) {
for(j = 0; j < 26; j++)
if(Map[j][i])
break;
if(j == 26 && App[i]) break;
}
if(i == 26) break;
App[i] = 0;
for(j = 0; j < 26; j++) Map[i][j] = 0;
printf("%c", i+'A');
}
if(n == 1) printf("%c", pre[0]);
puts("");
return 0;
}