【最小齿轮切换次数 spfa】URAL - 1930 Ivan's Car

Problem Description

输入n,m分别表示n个城市,m条道路。接下来m行每行输入u, v分别表示u,v之间有一条道路,但是u比较矮,v比较高。有两种齿轮模式,一种是低到高,一种是高到低。最开始齿轮模式未选择你可以自己选择那种。

**思路:1是上坡模式,0是下坡模式,开一个数组记录到这点是什么模式,后面比较一下是不是需要切换模式。基本就是最短路的模板了。

#include<bits/stdc++.h>
#define INF 0x3f3f3f
using namespace std;
struct node
{
    int to, w;
};
int n;
//分别记录该结点最小的齿轮切换次数,标记是否走过,到u这点是那种模式过来的。1为上坡模式,0为下坡模式
int dist[10005], vis[10005], dir[10005];
vector<node> Map[10005];//用vector存图,也可以使用前向星
void spfa(int u, int v)
{
    int x, y;
    memset(dist, INF, sizeof(dist));//初始化
    memset(dir, 0, sizeof(dir));
    memset(vis, 0, sizeof(vis));
    dist[u] = 0;
    vis[u] = 1;
    queue<int> q;
    for(int i = 0; i < Map[u].size(); i++)//处理一开始选择那种模式
    {
        x = Map[u][i].to, y = Map[u][i].w;
        dir[x] = y;//标记到x,是那种模式过来的
        dist[x] = 0;//一开始选择了y模式,所以初始化0
        q.push(x);//入队列
        vis[x] = 1;//标记走过
    }
    while(!q.empty())
    {
        u = q.front(); q.pop();
        vis[u] = 0;
        for(int i = 0; i < Map[u].size(); i++)
        {
            x = Map[u][i].to; y = Map[u][i].w;
            if(y == dir[u]) y = 0;//如果一样代表不需要切换齿轮
            else y = 1;//否则需要切换齿轮
            if(dist[x] > dist[u] + y)
            {
                dist[x] = dist[u] + y;//更新切换次数
                dir[x] = Map[u][i].w;//标记到这一点是什么模式
                if(!vis[x])
                {
                    vis[x] = 1;
                    q.push(x);
                }
            }
        }
    }
    printf("%d\n", dist[v]);

}
int main()
{
    int m, i, u, v;
    while(~scanf("%d %d", &n, &m))
    {
        for(i = 0; i < n; i++)
        {
            Map[i].clear();//初始化
        }
        while(m--)
        {
            scanf("%d %d", &u, &v);
            Map[u].push_back((node){v, 1});//上坡
            Map[v].push_back((node){u, 0});//下坡
        }
        scanf("%d %d", &u, &v);
        spfa(u, v);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值