【最小齿轮切换次数 spfa】URAL - 1930 Ivan's Car
2017-06-17 10:31
337 查看
Problem Description
输入n,m分别表示n个城市,m条道路。接下来m行每行输入u, v分别表示u,v之间有一条道路,但是u比较矮,v比较高。有两种齿轮模式,一种是低到高,一种是高到低。最开始齿轮模式未选择你可以自己选择那种。
**思路:1是上坡模式,0是下坡模式,开一个数组记录到这点是什么模式,后面比较一下是不是需要切换模式。基本就是最短路的模板了。
输入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; }
相关文章推荐
- ural 1930 Ivan's Car(spfa)
- ural 1930 Ivan's Car(spfa)
- URAL 1930 Ivan's Car
- Ivan's Car URAL - 1930——前向星+spfa算法
- GDUT Problem E: 逃票的chanming(2) SPFA (维护逃票次数最少基础上维护最小费用)
- spfa最短路 [URAL-1930]
- URAL 1930 Ivan's Car(BFS)
- 输入的最小按键次数
- POJ-3693--后缀数组求字典序最小重复次数最多子串
- Ural 1277 Cops and Thieves(最小点割集/最小割)
- Power Strings(KMP求最小循环的循环次数)
- 每天一道LeetCode-----将字符串切分,使每个子串都是回文串,计算所有可能结果和最小切分次数
- 算法-美团校招计算最小的相乘次数
- Ural-1076 Trash(最小费用最大流算法)
- 【Codeforces Round 363 (Div 2) D】【环套树 贪心 脑洞】Fix a Tree 每点一出度,最小修改次数使得变为反向有根树
- Ural 1277 cops ans thieves (最小割模型)
- ural 1930. Ivan's Car
- 面试题中的概率问题 - 数学期望(3) - 求最小值过程中元素替换次数的期望
- Java实现2路合并次序最小比较次数
- 【URAL 1004】 floyd最小环