/*
notice:
the graph may contain loops
between two point,there may be many ways that have different color
*/
#include <cstdio>
#include <deque>
using namespace std;
const int INF = 0x7ffffffe;
int n, m;
int r[201][201][4] = { 0 }; //r[x,y,c] edge form node x to node y has color c
int a[201][4] = { 0 }; //a[x,c] shortest path to node x , the last edge has color c
int mark[201] = { 0 }; // a marked node need to analyse
int findMark() {
for (int i=1; i<=n; ++i) {
if (mark[i] > 0) {
return i;
}
}
return 0;
}
int calcPath(int s, int c) {
int c1 = (c+1) % 3;
int c2 = (c+2) % 3;
if (c1 == 0) c1 = 3;
if (c2 == 0) c2 = 3;
return min(a[s][c1], a[s][c2]) + 1;
}
int main() {
scanf("%d%d", &n, &m);
for (int i=0; i<m; ++i) {
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
r[x][y][c] = 1;
}
for (int i=2; i<=n; ++i) {
a[i][1] = INF;
a[i][2] = INF;
a[i][3] = INF;
}
for (int s=1; s>0; s=findMark()) { //analyse every marked node, until there is no one
mark[s] = 0; //unmark this node, because it will be analysed
for (int i=1; i<=n; ++i) {
for (int c=1; c<=3; ++c) {
if (r[s][i][c] > 0) { //the edge form s to i which has color c exists
int ai = calcPath(s, c);
if (ai < a[i][c]) { //the current path to child node i is not the shortest
a[i][c] = ai;
mark[i] = s; // marked because its path length has been changed and need to analyse
}
}
}
}
}
int ans = min(a[n][1], min(a[n][2], a[n][3]));
if (ans >= INF) {
ans = -1;
}
printf("%d\n", ans);
return 0;
}
/*
4 4
1 2 1
2 3 2
3 4 3
1 3 3
3
4 4
1 2 1
2 3 2
3 4 3
2 4 1
3
3 2
1 2 1
2 3 1
-1
5 5
1 2 1
2 3 2
3 4 3
4 2 2
2 5 1
5
*/
sgu 226
最新推荐文章于 2018-06-28 10:17:51 发布