【最小齿轮切换次数 spfa】URAL

来源:互联网 发布:中国网络微电影有哪些 编辑:程序博客网 时间:2024/05/29 04:18

Problem Description

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

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

#include<bits/stdc++.h>#define INF 0x3f3f3fusing 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;}
原创粉丝点击