GBX的Graph(最短路)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GYH0730/article/details/82936191

Problem B: Graph

Time Limit: 2 Sec  Memory Limit: 128 MB
Submit: 1  Solved: 1
[Submit][Status][Web Board]

Description

There are n vertexs and m directed edges. Every vertex has a lowercase letters .Now, ZZT stand at 1.
he want to go to n to find ZZ.But ZZT dont like  character strings "cnm" ,"tmd","nsb". so  he won't walk such a continuous
3 vertex,the first vertex is 'c' second vertex is 'n'  last vertex is 'm'; He wanted to find her as soon as possible.

Input

The first line in the input will contain the number of cases ,Each case begins with two integer n,m(2<=n<=100,m<=1000)
then follow a line contain a character string "a1a2a3a4a5...an" ai is the i vertex's lowercase letter.
then follow m line ,each line contain li,ri,ci , a edge connect li and ri   cost time ci(1<=li,r1<=n,1<=ci<=100);

Output

for each case ,output a integer express the minimum time, if can't find ZZ output "-1"(without quotes);

Sample Input

1
4 4
cnmc
1 2 1
2 3 1
1 3 4
3 4 1

Sample Output

5

 

题意:给你一个n个点m条边的有向图,每一个点都有一个小写字母。现在ZZT站在点1,ZZ站在点n,ZZT想用最短的路程走到ZZ的地方。但是呢,ZZT不希望走过这样的连续的三点:cnm,tmd,nsb。现在问你他能否到达ZZ所在地。若能,输出最短路径,否则输出-1。

分析:此题关键在于如何构图。我们可以把边当点来使用,那么总共有m个点。加入一个源点0连向以点1发出去的边,加入一个汇点m+1使得点所有指向点n的边连向点m+1,那么原题就变成了从点0开始到达点m+1的最短路径。构图时,当两条边(u,v),(x,y)中 v == x 并且(str[u],str[v],str[y]) !=(c,n,m),(t,m,d),(n,s,b),则可连接。构图完毕,跑一遍最短路即可。

在其它博客无意中搜到的题,感觉挺巧妙的,把边看作了点,增加源点和汇点

原博客链接:https://blog.csdn.net/jhgkjhg_ugtdk77/article/details/47778893

原博客的题目链接失效了,找不提交的地方,就没写代码

扫描二维码关注公众号,回复: 3443321 查看本文章

猜你喜欢

转载自blog.csdn.net/GYH0730/article/details/82936191