hdu 5876 Sparse Graph icpc大连站网络赛 1009 补图最短路

时间:2022-05-24 00:42:58

BFS+链表

代码改自某博客

 #include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<map>
#include<set>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 2e5+;
const int INF = 0x3f3f3f3f;
const int A=INF;
const int B=;
typedef long long LL;
int h[maxn],e;
LL dis[maxn];
bool vis[maxn];
int start; struct Edge
{
int v,nxt,w;
} E[maxn<<]; void init()
{
e=;
memset(h,-,sizeof h);
memset(vis,false,sizeof vis);
} void add(int u,int v,int w)
{
E[e].v = v;
E[e].w = w;
E[e].nxt = h[u];
h[u] = e++;
} struct QNode
{
int v,c;
QNode(int _v,int _c)
{
v = _v;
c=_c;
}
bool operator < (const QNode &a) const
{
return c>a.c;
}
}; void dijkstra(int n)
{
memset(dis,INF,sizeof dis);
priority_queue<QNode>Q;
dis[] = ;
Q.push(QNode(,));
while(!Q.empty())
{
QNode tmp = Q.top();
Q.pop();
int u = tmp.v;
if(vis[u]) continue;
vis[u] = true;
for(int i=h[u]; ~i; i=E[i].nxt)
{
int v = E[i].v;
int w = E[i].w;
if(vis[v]) continue;
if(dis[u]+w<dis[v])
{
dis[v] = dis[u]+w;
Q.push(QNode(v,dis[v]));
}
}
}
} void BFS(int n,LL val)
{
set<int>ta,tb;
queue<int>Q;
Q.push(start);
dis[start] = ,dis[n] = INF;
for(int i=; i<=n; i++){
if(i==start) continue;
ta.insert(i);
}
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i=h[u]; ~i; i=E[i].nxt)
{
int v = E[i].v;
if(!ta.count(v)) continue;
ta.erase(v);
tb.insert(v);
}
for(set<int>::iterator it=ta.begin(); it!=ta.end(); it++)
{
Q.push(*it);
dis[*it] = dis[u] + val;
}
ta.swap(tb);
tb.clear();
}
} int main()
{
int N,M,T;
int u,v;
while(scanf("%d",&T)!=EOF)
{
while(T--)
{
scanf("%d%d",&N,&M);
init();
bool flag = false;
for(int i=; i<M; i++)
{
scanf("%d%d",&u,&v);
add(u,v,A);
add(v,u,A); }
scanf("%d",&start);
dijkstra(N);
BFS(N,B);
bool first=;
for(int i=;i<=N;i++)
{
if(i==start) continue;
if(first) printf(" ");
printf("%d",dis[i]);
first=;
}
printf("\n");
}
}
return ;
} /* 1
2 0
1 */