题意:给定n个城镇以及m条道路,每条道路连接两个城镇,道路有上下两种状态,求起点到终点需要的最少转换状态次数
思路:令dp[i][0/1]为到达第i个城镇当前是上坡或者下坡的最少转换次数,然后无脑spfa就可以了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 10000+7;
int n,m,s,t;
vector<pair<int,int> >e[maxn];
int dp[maxn][2];
int vis[maxn];
void spfa()
{
queue<int>q;
for(int i = 0;i<=n;i++)
for(int j= 0;j<2;j++)
dp[i][j]=1e9;
q.push(s);
dp[s][0]=dp[s][1]=0;
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u]=0;
for(int i = 0;i<e[u].size();i++)
{
pair<int,int> t = e[u][i];
int v = e[u][i].first;
int w = e[u][i].second;
if(dp[v][w] > min(dp[u][w],dp[u][w^1]+1))
{
dp[v][w]=min(dp[u][w],dp[u][w^1]+1);
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
e[u].push_back(make_pair(v,0));
e[v].push_back(make_pair(u,1));
}
scanf("%d%d",&s,&t);
spfa();
printf("%d\n",min(dp[t][1],dp[t][0]));
}
The world is in danger! Awful earthquakes are detected all over the world. Houses are destroyed, rivers overflow the banks, it is almost impossible to move from one city to another. Some roads are still useful, but even they became too steep because of soil movements.
Fortunately, engineer Ivan has a car, which can go well uphill and downhill. But there are different gear-modes for movement up and down, so during the driving you have to change gear-modes all the time. Also engineer Ivan has a good friend –– geologist Orlov. Together they are able to invent a plan for world saving. But, unfortunately, geologist Orlov lives in another town.
Ivan wants to save the world, but gear-box in his car started to wear out, so he doesn’t know, how long he will be able to use it. Please help Ivan to save the world. Find a route to the Orlov's town, such that Ivan will have to change gear-modes as few times as possible. In the beginning of the way Ivan can turn on any of gear-modes and you don't have to count this action as a changing of gear-mode.
There are two positive integer numbers
n and
m in the first line, the number of towns and roads between them respectively
(2 ≤
n ≤ 10 000;
1 ≤
m ≤ 100 000).
Next
m lines contain two numbers each — numbers of towns, which are connected by road. Moreover, the first is the town, which is situated below, from which you should go uphill by this road. Every road can be used for traveling in any of two directions. There is at most one road between any two cities. In the last line there are numbers of two cities, in which Ivan and geologist Orlov live, respectively. Although the majority of roads were destroyed, Ivan knows exactly, that the way to geologist Orlov's city exists.
Output the smallest number of gear-modes changes on the way to Orlov's city.
input | output |
---|---|
3 2 1 2 3 2 1 3 | 1 |
3 3 1 2 2 3 3 1 1 3 | 0 |