n<=2e5
scanf printf比cin cout快5倍
autotoNumber = [&] (string const &s)->unsigned{…}
#include
using namespace std;
typedef long long ll;
const int maxn=2e5+5;
const int mod=1000;
const int INF=0x3f3f3f3f;
typedef pair<int,int> pii;
int t,n,m,k,ans,maxx;
string s;
vector<int> g[maxn];
int d1[maxn],d2[maxn];
bool keyv[maxn]; //打标记
void bfs(int dist[],int s){
dist[s]=0;
queue<int> q;
q.push(s);
while(!q.empty()){
int u=q.front();
q.pop();
for(int &v: g[u]){
if(dist[v]==-1){
q.push(v);
dist[v]=dist[u]+1;
}
}
}
}
int main(){
scanf("%d %d %d",&n,&m,&k);
for(int i=1;i<=k;i++){
scanf("%d",&t);
keyv[t]=true;
}
for(int i=1,u,v;i<=m;i++){
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
memset(d1,-1,sizeof d1);
memset(d2,-1,sizeof d2);
bfs(d1,1);//1号点到其他点的最短路
bfs(d2,n);//n号点到其他点的最短路
vector<pii> v;
for(int i=1;i<=n;i++){ //k个没有用数组记录
if(keyv[i]){
// v.push_back({d1[i],d2[i]});//1-i n-i最短路
v.emplace_back(d1[i],d2[i]);
}
}
sort(v.begin(),v.end(),[&](const pii &a,const pii &b){
return a.first-a.second<b.first-b.second;
});
maxx=v[0].first;
for(int i=1;i<v.size();i++){
ans=max(ans,maxx+1+v[i].second);
maxx=max(maxx,v[i].first);
}
printf("%d\n",min(ans,d1[n]));
return 0;
}
链式向前星
#include
using namespace std;
const int Maxn = 200005;
int n, m, k, ct, p1, p2, las, ans, cnt, a[Maxn], dis1[Maxn], dis2[Maxn], head[Maxn], from[Maxn], b[Maxn];
bool vis[Maxn], vis2[Maxn];
struct edg
{
int nxt, to;
} edge[2 * Maxn];
void add(int x, int y)
{
edge[++cnt] = (edg){head[x], y};
head[x] = cnt;
}
queue <int> Qu;
void bfs(int dis[], int s)
{
memset(dis, 0x3f, sizeof(int[n + 1]));
dis[s] = 0;
Qu.push(s);
while (!Qu.empty())
{
int u = Qu.front();
Qu.pop();
for (int i = head[u]; i; i = edge[i].nxt)
{
int to = edge[i].to;
if (dis[u] + 1 < dis[to])
{
dis[to] = dis[u] + 1;
from[to] = u;
Qu.push(to);
}
}
}
}
int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= k; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
add(x, y);
add(y, x);
}
bfs(dis1, 1);
bfs(dis2, n);
sort(a + 1, a + 1 + k, [](int x, int y){return dis1[x] < dis1[y];});
for (int i = 2; i <= k; i++)
ans = max(ans, min(dis1[n], 1 + dis1[a[i - 1]] + dis2[a[i]]));
printf("%d", ans);
return 0;
}