成语接龙(Idiomatic Phrases Game)

2023-05-16

Idiomatic Phrases Game

Problem Description

Tom is playing a game called Idiomatic Phrases Game. An idiom consists of several Chinese characters and has a certain meaning. This game will give Tom two idioms. He should build a list of idioms and the list starts and ends with the two given idioms. For every two adjacent idioms, the last Chinese character of the former idiom should be the same as the first character of the latter one. For each time, Tom has a dictionary that he must pick idioms from and each idiom in the dictionary has a value indicates how long Tom will take to find the next proper idiom in the final list. Now you are asked to write a program to compute the shortest time Tom will take by giving you the idiom dictionary.  
 

Input
The input consists of several test cases. Each test case contains an idiom dictionary. The dictionary is started by an integer N (0 < N < 1000) in one line. The following is N lines. Each line contains an integer T (the time Tom will take to work out) and an idiom. One idiom consists of several Chinese characters (at least 3) and one Chinese character consists of four hex digit (i.e., 0 to 9 and A to F). Note that the first and last idioms in the dictionary are the source and target idioms in the game. The input ends up with a case that N = 0. Do not process this case.  
 

Output
One line for each case. Output an integer indicating the shortest time Tome will take. If the list can not be built, please output -1.
 

Sample Input

  
  
5 5 12345978ABCD2341 5 23415608ACBD3412 7 34125678AEFD4123 15 23415673ACC34123 4 41235673FBCD2156 2 20 12345678ABCD 30 DCBF5432167D 0
 

Sample Output

  
  
17 -1

成语接龙 分数:5

时间限制:1 秒
内存限制:32 兆
特殊判题:

标签

  • Dijkstra最短路径

题目描述

小明在玩成语接龙的游戏。成语接龙的规则是,如果成语A的最后一个汉字与成语B的第一个汉字相同,那么成语B就可以接到成语A的后面。
小明现在手上有一本成语词典,每次他都得花费一定时间来从当前的成语查到下一个可以接在后面的成语。
现在给你一个成语列表,请你计算从列表中的第一个成语开始,到接到列表中的最后一个成语最少需要多长时间。

输入格式

输入包含多组测试数据。
每组输入第一行是一个整数N(0<N<1000),表示成语列表的长度。
接下来N行,每行先输入一个整数T,再输入一个字符串S。
S表示一条成语,T表示小明从S查到下一个成语所花费的时间。
每条成语由至少3个汉字组成,每个汉字由4个十六进制数(0~9和A~F)组成。
当N=0时,输入结束。

输出

对于每组输入,输出从列表中的第一个成语开始,到接到列表中的最后一个成语需要的最少时间。
如果无法连接到列表中的最后一个成语,则输出-1。

样例输入

5
5 12345978ABCD2341
5 23415608ACBD3412
7 34125678AEFD4123
15 23415673ACC34123
4 41235673FBCD2156
2
20 12345678ABCD
30 DCBF5432167D
0

样例输出

17
-1

【分析】

       这道题用到了图的知识与Dijkstra算法(单源最短路径)。

       在这里附上来自于 海 子 的Dijkstra算法分析:点击打开链接

用java语言编写程序,代码如下:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while(input.hasNext()) {
			int n = input.nextInt();
			if(n == 0) break;
			
			int[] w = new int[n];
			String[] str = new String[n];
			
			for(int i = 0; i < n; i++) {
				w[i] = input.nextInt();
				str[i] = input.next();
			}
			
			//创建图——将字符串看成是顶点,而顶点的值是它所处的位置,而边则是两个能够匹配的字符串构成的“边”,
			//边的权值则是从第一个字符串到另一个匹配字符串的时间
			//g[i][j]表示从顶点i到顶点j所构成的边的权值,如果顶点i不能构成边,则权值赋值为最大值。
			int[][] g = new int[n][n];
			for(int i = 0; i < n; i++)
				for(int j = 0; j < n; j++) {
					int len = str[i].length();
					if(str[j].charAt(0) == str[i].charAt(len - 4) &&
							str[j].charAt(1) == str[i].charAt(len - 3) &&
							str[j].charAt(2) == str[i].charAt(len - 2) &&
							str[j].charAt(3) == str[i].charAt(len - 1))
						g[i][j] = w[i];
					else
						g[i][j] = Integer.MAX_VALUE;
				}
			
			int[] dist = new int[n];
			//单源最短路径算法
			Dijkstra(n, g, dist);
			if(dist[n - 1] != Integer.MAX_VALUE)
				System.out.println(dist[n - 1]);
			else
				System.out.println(-1);
		}
	}
	
	public static void Dijkstra(int n, int[][] g, int[] dist) {
		boolean[] isVisited = new boolean[n];
		for(int i = 0; i < n; i++)
			dist[i] = g[0][i];
		dist[0] = 0;
		isVisited[0] = true;
		for(int i = 1; i < n; i++) {
			int min = Integer.MAX_VALUE;
			int u = 0;
			for(int j = 0; j < n; j++) {
				if(dist[j] < min && !isVisited[j]) {
					min = dist[j];
					u = j;
				}
			}
			
			isVisited[u] = true;
			for(int j = 0; j < n; j++) {
				if(g[u][j] != Integer.MAX_VALUE && dist[u] + g[u][j] < dist[j] && !isVisited[j])
					dist[j] = dist[u] + g[u][j];
			}
		}
	}
}

另外这里还有一种时间超限的答案:(其中,同样是运用到了Dijkstra算法,只是实现不同罢了)

用java语言编写程序,代码如下:

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
//1124:成语接龙(时间超限)——Dijkstra最短路径

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(new BufferedInputStream(System.in));
		while(input.hasNext()) {
			int n = input.nextInt();
			if(n == 0) break;
			
			int source = 0, end = 0;
			boolean[] isExist = new boolean[70000];
			int numberOfVertices = 0;
			
			PriorityQueue<WeightEdge>[] q = new PriorityQueue[70000];
			for(int i = 0; i < n; i++) {
				int t = input.nextInt();
				String s = input.next();
				int u = Integer.valueOf(s.substring(0, 4), 16);
				int v = Integer.valueOf(s.substring(s.length() - 4, s.length()), 16);
				WeightEdge edge = new WeightEdge(u, v, t);
				
				if(i == 0)
					source = u;
				if(i == n - 1)
					end = u;
				
				if(isExist[u] == false) {
					isExist[u] = true;
					numberOfVertices++;
				}
				
				if(q[u] == null) {
					q[u] = new PriorityQueue<WeightEdge>();
				}
				q[u].add(edge);
			}
			
			if(n == 1) {
				System.out.println(0);
				continue;
			}
			int[] dist = new int[70000];
			getShortestPath(source, end, numberOfVertices, dist, q);
			if(dist[end] == Integer.MAX_VALUE)
				System.out.println(-1);
			else
				System.out.println(dist[end]);
		}
	}
	
	static class WeightEdge implements Comparable<WeightEdge> {
		int u, v, weight;
		public WeightEdge(int u, int v, int weight) {
			this.u = u;
			this.v = v;
			this.weight = weight;
		}
		
		public int compareTo(WeightEdge o) {
			return (weight - o.weight);
		}
	}
	
	public static void getShortestPath(int sourceIndex, int end, int numberOfVertices,
			int[] dist, PriorityQueue<WeightEdge>[] queues) {
		List<Integer> T = new ArrayList<Integer>();
		T.add(sourceIndex);
		
		for(int i = 0; i < dist.length; i++)
			dist[i] = Integer.MAX_VALUE;
		dist[sourceIndex] = 0;
		
		while(T.size() < numberOfVertices) {
			int v = -1;
			int smallestDist = Integer.MAX_VALUE;
			for(int u : T) {
				if(queues[u] == null)
					continue;
				
				while(!queues[u].isEmpty() && T.contains(queues[u].peek().v))
					queues[u].remove();
				
				if(queues[u].isEmpty())
					continue;
				
				WeightEdge e = queues[u].peek();
				if(dist[u] + e.weight < smallestDist) {
					v = e.v;
					smallestDist = dist[u] + e.weight;
				}
			}
			
			if(v != -1) {
				T.add(v);
				dist[v] = smallestDist;			
				if(v == end)
					return;
			}
		}
	}
}



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

成语接龙(Idiomatic Phrases Game) 的相关文章

  • 反片语(Ananagrams)

    反片语 Ananagrams 输入一些单词 xff0c 找出所有满足如下条件的单词 xff1a 该单词不能通过字母重排 xff0c 得到输入文本中的另外一个单词 在判断是否满足条件时 xff0c 字母不分大小写 xff0c 但在输出时应保留
  • 集合栈计算机(The SetStack Computer)

    The SetStack Computer Time limit 3 000 seconds 题目是这样的 xff1a 有一个专门为了集合运算而设计的 集合栈 计算机 该机器有一个初始为空的栈 xff0c 并且支持以下操作 xff1a PU
  • 代码对齐(Alignment of Code)

    Alignment of Code Time Limit 4000 2000 MS Java Others Memory Limit 32768 32768 K Java Others Total Submission s 958 Acce
  • Ducci序列(Ducci Sequence)

    Ducci Sequence Time limit 3 000 seconds A Ducci sequence is a sequence of n tuples of integers Given an n tuple of integ
  • 卡片游戏(Throwing cards away I)

    Problem B Throwing cards away I Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at

随机推荐

  • 交换学生(Foreign Exchange)

    Problem E Foreign Exchange Input standard input Output standard output Time Limit 1 second Your non profit organization
  • CAN通信物理容错测试checklist

    CAN通信物理容错测试checklist 工作项目中 xff0c 我们有时有些产品CAN总线功能 xff0c 一般情况下我们必须要满足以下几种状况的测试项才算符合要求 一 CAN H与CAN L短路 判定标准 xff1a 短接故障发生后 x
  • 对称轴(Symmetry)

    Symmetry Time limit 3 000 seconds The figure shown on the left is left right symmetric as it is possible to fold the she
  • 打印队列(Printer Queue)

    Printer Queue Time limit 3 000 seconds 分析 首先记录所求时间它在队列中的位置 xff0c 用一个队列存储这些任务的优先级 xff0c 同时也创建一个队列存储对应任务一开始的位置 xff0c 那么当我们
  • 更新字典(Updating a Dictionary)

    Updating a Dictionary Time Limit 1000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description In th
  • 铁轨(Rails)

    Rails Time limit 3 000 seconds Rails There is a famous railway station in PopPush City Country there is incredibly hilly
  • 矩阵链乘(Matrix Chain Multiplication)

    Matrix Chain Multiplication Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description
  • 天平(Not so Mobile)

    Not so Mobile Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Before being
  • 下落的树叶(The Falling Leaves)

    The Falling Leaves Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Each yea
  • 四分树(Quadtrees)

    Quadtrees Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description A quadtree is a r
  • 油田(Oil Deposits)

    Oil Deposits Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description The GeoSurvCom
  • Abbott的复仇(Abbott's Revenge)

    Abbott 39 s Revenge Time limit 3 000 seconds Abbott s Revenge Abbott s Revenge The 1999 World FinalsContest included a p
  • rockchip rk3568 openwrt修改根文件系统分区

    rk3568的openwrt根文件系统分区大小如何修改 xff1f 1 rootfs大小取决于rk356x config的配置 xff0c 默认CONFIG TARGET ROOTFS PARTSIZE 61 512 xff0c 如果需要修
  • 除法(Division)

    Division Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Write a program th
  • 最大乘积(Maximum Product)

    Maximum Product Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Problem D M
  • 分数拆分(Fractions Again?!)

    Fractions Again Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Problem A F
  • 二叉树(Tree Recovery)

    Tree Recovery Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Little Valent
  • 骑士的移动(Knight Moves)

    Knight Moves Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description A friend of yo
  • 单词(Play On Words)

    分析 首先需对欧拉道路有所了解 存在欧拉道路的充分条件 xff1a 对于无向图而言 xff0c 如果一个无向图是连通的 xff0c 且最多只有两个奇点 xff08 顶点的度数为奇数 xff09 xff0c 则一定存在欧拉道路 如果有两个奇点
  • 成语接龙(Idiomatic Phrases Game)

    Idiomatic Phrases Game Problem Description Tom is playing a game called Idiomatic Phrases Game An idiom consists of seve