spfa求最短路径

Alice and Bob are playing a game on a simple connected graph with N nodes and M edges.
Alice colors each edge in the graph red or blue.
A path is a sequence of edges where each pair of consecutive edges have a node in common. If the first edge in the pair is of a different color than the second edge, then that is a ‘‘color change.’’
After Alice colors the graph, Bob chooses a path that begins at node 1 and ends at node N. He can choose any path on the graph, but he wants to minimize the number of color changes in the path. Alice wants to choose an edge coloring to maximize the number of color changes Bob must make. What is the maximum number of color changes she can force Bob to make, regardless of which path he chooses? changes she can force Bob to make, regardless of which path he chooses?
输入描述:
The first line contains two integer values N and M with 2 \le N \le 100,0002≤N≤100000 and 1 \le M \le 100,0001≤M≤100000. The next M lines contain two integers a_ia
All edges in the graph are unique.
输出描述:
Output the maximum number of color changes Alice can force Bob to make on his route from node 1 to node N.
示例1
输入
3 3
1 3
1 2
2 3
输出
0
示例2
输入
7 8
1 2
1 3
2 4
3 4
4 5
4 6
5 7
6 7
输出
3
不知道为啥牛客网粘贴过来有一些乱码,大概题意就是有n个点m条边,求1-n的最短路,但是1<=n<=100000,1<=m<=1000000。所以不能开二维数组用dijk去写最短路,只能用邻接表存图,spfa求最短路径。

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int head,first[200010],to[200010],book[200010],nx[200010];
struct node
{
    int x,s;
}u,v;
void add(int x,int y)
{
    nx[head]=first[x];
    first[x]=head;
    to[head++]=y;
}
int main()
{
    int n,m,x,y;
    memset(first,-1,sizeof(first));
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        add(x,y);
        add(y,x);
    }
    queue<node>q;
    u.x=1;
    u.s=0;
    book[1]=0;
    q.push(u);
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        if(u.x==n)
        {
            printf("%d\n",u.s-1);
            break;
        }
        for(int i=first[u.x];i!=-1;i=nx[i])
        {
            int k=to[i];
            if(!book[k])
            {
                v.x=k;
                v.s=u.s+1;
                q.push(v);
                book[k]=1;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值