火星文字典 您所在的位置:网站首页 暗黑二hackmap怎么用 火星文字典

火星文字典

2023-12-08 20:02| 来源: 网络整理| 查看: 265

题目大意

已知一种新的火星文的单词由英文字母(仅小写字母)组成,但是此火星文中的字母先后顺序未知。给出一组非空的火星文单词,且此组单词已经按火星文字典序进行好了排序(从小到大),请推断出此火星文中的字母先后顺序。

输入描述:

一行文本,为一组按火星文字典序排序好的单词(单词两端无引号),单词之间通过空格隔开。

输出描述:

按火星文字母顺序输出出现过的字母,字母之间无其他字符,如果无法确定顺序或者无合理的字母排序可能,请输出"invalid"(无需引号)。

输入例子1:

z  x

输出例子1:

zx

输入例子2:

wrt  wrf  er  ett  rftt

输出例子2:

wertf

输入例子3:

z  x  z

输出例子3:

invalid

分析

先把每个单词取出来,因为单词是排好序的,所以临近两个单词,从左边开始,只看第一个不一样的字符,转换为int型,假设为a,b,然后如果这两个数之前没有比较过,那么deg[b]++,最后拓扑排序就可以了。主要是怎么获得deg[]数组的值。在拓扑排序里面,队列里一开始只加入第一个单词的第一个字符,其他度为0的先不加,例如:wf ec ef,我们能比较出w在e前面,c在f前面,但是w和c我们却不知道顺序。

代码 import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); static int N = 1005; static String word[] = new String[N]; static int deg[] = new int[30]; static boolean mp[][] = new boolean[30][30]; static boolean vis[] = new boolean[30]; static int cnt = 0; static int sum = 0; public static void main(String[] args) { String str; str = sc.nextLine(); init(); get_word(str); get_deg(); tuopu(); } static void init() { for(int i = 0; i < N; i++) { word[i] = ""; // 初始值是null } } static void get_word(String str) { // 把每个单词取出来 char c; int num; for(int i = 0; i < str.length(); i++) { c = str.charAt(i); if(c != ' ') { word[cnt] += c; num = (int)(c - 'a'); if(vis[num] == false) { vis[num] = true; sum++; // 统计出现了多少种字符 } } else { cnt++; } } } static void get_deg() { int a, b; for(int i = 0; i < cnt; i++) { for(int j = 0; j < word[i].length(); j++) { if(word[i + 1].length() - 1 >= j) { a = (int)(word[i].charAt(j) - 'a'); b = (int)(word[i + 1].charAt(j) - 'a'); if(a != b) { if(mp[a][b] == false) { // 确保不会重复 mp[a][b] = true; deg[b]++; } break; } } } } } static void tuopu() { Queue queue = new LinkedList(); queue.add((int)(word[0].charAt(0) - 'a')); int count = 0, tmp; String ans = ""; while(queue.isEmpty() == false) { tmp = queue.peek(); queue.remove(); ans += (char)(tmp + 'a'); count++; for(int i = 0; i < 30; i++) { if(mp[tmp][i]) { deg[i]--; if(deg[i] == 0) { queue.add(i); } } } } if(count != sum) { System.out.println("invalid"); } else { System.out.println(ans); } } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有