sgu 226

/*
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

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值