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.
InputThe 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.
OutputOutput the length of the shortest path between the first and the N-th vertexes. Output "-1" if the path doesn't exist.
Sample tests
InputTest #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
OutputTest #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/ 转载请注明出处