跳到正文

题解

P1811 最短路

stars_rain约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月16日
篇幅
约 5 分钟
题目
P1811

版本

  1. v1当前

思考方向:由于数据过水,考虑搜索做法

这道题如果用 bfsbfs 做不需要任何剪枝。

首先我们要明确需要哪些参数,一共需要 33 个变量和 11 个数组。三个变量分别表示当前走了几步( ansans ),当前节点( xx ),以及他的父亲节点(prtprt),另外一个数组用来记录路径(vv)

结束条件: xx ==== nn 的时候,就输出路径数组

循环遍历每一个搜索可能,也就是从当前节点能通向哪些节点, 注意此题 bfsbfs 不需要标记数组 通过样例可以知道 一个节点可能会重复经过很多次 ,所以不需要。

于是判断是否是一个搜索可能就是判断有没有在三元组内即可。

这里给出两个个判断三元组的方法

  1. mapmap 没有学过map的请点这里 来源:oi-wiki

重载运算符,可以是大于也可以是小于也能使用自带的函数 tietie ,但是 必须有序 ,因为后面查询需要用到

查询的时候使用自带函数 findfind , 这里给出使用案例

C++
struct ther{
    int a,b,c;
    bool operator<(const ther& dd) const {
        return tie(a, b, c) < tie(dd.a, dd.b, dd.c);
    }
};
map<ther,bool> t;

ther w;
if(t.find(w)!=t.end()) //不存在
else //存在
  1. 二分+结构体排序

可以先给三元组按照小于进行排序,然后单独再拿三个数组存下,在查询的时候只需要用两个函数结合结合起来即可。

给出两个函数使用方法

代码
upper_bound(数组名+起始位置,数组名+结束位置,查询元素)-数组名   返回值为第一个大于查询元素的下标
lower_bound(数组名+起始位置,数组名+结束位置,查询元素)-数组名   返回值为第一个大于等于查询元素的下标

最后晒上AC代码,撒花完结

C++
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
struct edge{
    int to,next;
}e[40005];
int xb,h[3005];
struct node{
    int ans,x,prt;
    vector<int> v;
};
struct ther{
    int a,b,c;
    bool operator<(const ther& dd) const {
        return tie(a, b, c) < tie(dd.a, dd.b, dd.c);
    }
};
void merge(int x,int y){
    xb++;
    e[xb]={y,h[x]};
    h[x]=xb;
}
map<ther,bool> t;
queue<node> q;
vector<int> u;
void bfs(){
    u.push_back(1);
    q.push({0,1,0,u});
    while(!q.empty()){
        node f=q.front();
        u=f.v;
        q.pop();
        if(f.x==n){
            cout<<f.ans<<endl;
            int ed=f.v.size();
            for(int i=0;i<ed;i++){
                cout<<f.v[i]<<" ";
            }
            return ;
        }
        for(int i=h[f.x];i!=-1;i=e[i].next){
            ther w={f.prt,f.x,e[i].to};
            if(t.find(w)==t.end()){
                u.push_back(e[i].to);
                q.push({f.ans+1,e[i].to,f.x,u});
                u=f.v;
            }
        }
    }

}
int main(){
    cin>>n>>m>>k;
    for(int i=1;i<=n;i++)h[i]=-1;
    for(int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        merge(x,y);
        merge(y,x);
    }
    for(int i=1;i<=k;i++){
        int a,b,c;
        cin>>a>>b>>c;
        ther w={a,b,c};
        t[w]=1;
    }
    bfs();
    return 0;
}
原文