sgu226. Colored graph

题意:

给你一个n(n<=200)个点,m(m<=n*n)的有向图,然后每条边都有一个颜色,然后要求求出1->n的一条最短路径,满足相邻的两条边不能是同一种颜色。输出最短路径长度。

tip:

bfs vis多加一维来的颜色。。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 210;
int tot,head[maxn],vis[maxn][5];
struct node{
    int v,next,c;
}edges[maxn*maxn];
void add(int u,int v,int c){
    edges[tot].v = v;edges[tot].c = c;edges[tot].next = head[u];head[u] = tot++;
}
int u,v,c,n,m;
void init(){
    tot = 0;
    for(int i = 1; i <= n ; i++)
        head[i] = -1;
    for(int i = 1; i <= m; i++){
        scanf("%d%d%d",&u,&v,&c);
        add(u,v,c);
    }
}
typedef pair<int,int>pii;
int step[maxn][5];
void bfs(){
    queue<pii> q;
    memset(vis,0,sizeof(vis));
    q.push(make_pair(1,0));vis[1][0] = 1;step[1][0] = 0;
    while(!q.empty()){
        pii tmp = q.front();q.pop();
        if(tmp.first == n){
            printf("%d\n",step[tmp.first][tmp.second]);
            return ;
        }
        for(int k = head[tmp.first] ; k != -1 ; k = edges[k].next){
            int v = edges[k].v,c = edges[k].c;
            if(!vis[v][c] && c != tmp.second){
                vis[v][c] = 1;
                q.push(make_pair(v,c));
                step[v][c] = step[tmp.first][tmp.second]+1;
            }
        }
    }
    printf("-1\n");
}
int main(){
    while(~scanf("%d%d",&n,&m)){
        init();
        bfs();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值