[JLOI2011]飞行路线

本文介绍了一种最短路径算法的实现与优化方法,通过调整距离矩阵定义与操作过程,实现了考虑特定条件下部分节点免费通行的最短路径计算。代码采用C++编写,并通过样例输入展示了算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

最短路,给起点和终点,前k个点免费。

Sample Input

5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100

Sample Output

8

只要改一下d的定义,d[i][k],表示到第i个点,用k次免费。然后改操作,即可。

#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
    int x,y,d,next;
}a[210000];int len,last[110000];
void ins(int x,int y,int d)
{
    len++;
    a[len].x=x;a[len].y=y;a[len].d=d;
    a[len].next=last[x];last[x]=len;
}
struct linode
{
    int x,hh;
}list[210000];
int d[11000][20];
bool v[11000][20];
int main()
{
    int n,m,K,st,ed,x,y,c;
    scanf("%d%d%d",&n,&m,&K);
    scanf("%d%d",&st,&ed);st++;ed++;
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&c);x++;y++;
        ins(x,y,c);ins(y,x,c);
    }
    memset(v,false,sizeof(v));v[st][0]=true;
    for(int i=1;i<=n;i++)for(int j=0;j<=K;j++)d[i][j]=999999999;
    d[st][0]=0;list[1].x=st;list[1].hh=0;
    int head=1,tail=2,ans=999999999;
    while(head!=tail)
    {
        x=list[head].x;int hh=list[head].hh;
        if(x==ed){if(d[x][hh]<ans)ans=d[x][hh];}
        for(int k=last[x];k;k=a[k].next)
        {
            y=a[k].y;
            if(d[y][hh]>d[x][hh]+a[k].d)
            {
                d[y][hh]=d[x][hh]+a[k].d;
                if(v[y][hh]==false)
                {
                    v[y][hh]=true;
                    list[tail].x=y;list[tail].hh=hh;
                    tail++;if(tail==200001)tail=1;
                }
            }
            if(hh+1<=K&&d[y][hh+1]>d[x][hh])
            {
                d[y][hh+1]=d[x][hh];
                if(v[y][hh+1]==false)
                {
                    v[y][hh+1]=true;
                    list[tail].x=y;list[tail].hh=hh+1;
                    tail++;if(tail==200001)tail=1;
                }
            }
        }
        v[x][hh]=false;
        head++;if(head==200001)head=1;
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值