SGU 226. Colored graph

226. Colored graph

time limit per test: 0.25 sec.
memory limit per test: 4096 KB

You are given an oriented graph. Each edge of the graph is colored in one of the three colors. Your task is to find the length of the shortest path from the first vertex to the N-th. Note that any two successive edges in the path can't have the same color.


Input

The first line of the input file consists of two integers N and M (2 <= N <= 200; 0 <= M <= N*N). Next M lines contain descriptions of the edges. Each edge description is a list of three integers X, Y, C (1 <= X, Y <= N, 1 <= C <= 3), where X is the starting vertex of the edge, Y is the finishing vertex and C is the color of the edge.


Output

Output the length of the shortest path between the first and the N-th vertexes. Output "-1" if the path doesn't exist.


Sample tests


Input

Test #1 
4 4 
1 2 1 
2 3 2 
3 4 3 
2 4 1 

Test #2 
3 2 
1 2 1 
2 3 1 


Output

Test #1 
3 

Test #2 
-1 

概述

    N(2 ≤ N ≤ 200)个顶点,最大N^2个有色有向无权边,相邻同色边无法通过,求两点最短距离。

思路

    BFS搜索,只是颜色从1维增加到3维。注意模型需要保证无后效性。我用en[i][j]表示第i个点下一步可以走第j个颜色的边

代码

    一开始写成无向图搜索WA调了好半天 ..可优化的地方依然很多。

#include<bits\stdc++.h> 
typedef long long ll;
using namespace std; 

const int N = 200+5;
bool en[N][3]={0};
bool cur[2][N][3]={0};
bool curp=0;

struct edge{
	int a;
	int b;
	int c;
	bool e;
}e[40000+5];

int main()  
{
	int n,m;
	int i,j,k;
	cin>>n>>m;
	for(i=0;i<m;i++){
		cin>>e[i].a>>e[i].b>>e[i].c;
		e[i].c--;
		e[i].e=1;
	}
	for(i=0;i<3;i++){
		cur[curp][1][i]=1;
		en[1][i]=1;
	}
	int l=0;
	bool end=0,finish=0;
	while(!end && !finish){
		end=1;
		l++;
		for(i=0;i<m;i++) if(e[i].e)
			if(cur[curp][e[i].a][e[i].c]){
				for(k=0;k<3;k++) if(e[i].c!=k && !en[e[i].b][k]){
					cur[!curp][e[i].b][k]=1;
					en[e[i].b][k]=1;
					e[i].e=0;
					if(e[i].b==n){
						finish=1;
						break;
					}}
				end=0;		
			}
		memset(cur[curp],0,sizeof(cur[curp]));
		curp=!curp;
	}
	if(finish) cout<<l;
	else cout<<-1;
	return 0;
}

http://www.cnblogs.com/hizcard/  转载请注明出处

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值