分析:
给出一个原图G,点数为n,边数为m,给出一个起点s,求在其补图H(即G中有的边H没有,G没有的边H有)中从s出发到另外N-1个点的最短路。(所有边权为1)。题解:
先把起点S加入队列,然后顺序取出队列里的点k,遍历原图G中k能抵达的点,标记这些点,然后对除这些点和已经访问过的点外的点求最短路并加入队列中,再重复。教训:
非常坑的是做题时没看清楚输出是“print a single line consisting of N−1 space separated integers,”然后我是每个数一行一行输出的,直接导致整场比赛都在TLE。。。。。T_T,然后结束后一改输出直接AC了 (生无可恋.jpg)AC代码:
/*************************************************************************
> File Name: test.cpp
> Author: Akira
> Mail: qaq.febr2.qaq@gmail.com
************************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cmath>
#include <vector>
#include <set>
#include <list>
#include <ctime>
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) ((a)*(a))
using namespace std;
#define MaxN 200005
#define MaxM 200000
#define INF 0x3f3f3f3f
#define bug cout<<88888888<<endl;
int T;
int N,M;
struct Edge
{
int u,v;
int next;
}edge[MaxM];
int head[MaxN];
int cont;
void add(int u, int v)
{
edge[cont].v = v;
edge[cont].u = u;
edge[cont].next = head[u];
head[u] = cont++;
}
void Add(int u, int v) //添加u-v,权重为cost的边,这个建的是双向,可以改
{
add(u, v);
add(v, u);
}
void init() //!!!!!!!!每次建图前记得init!!!
{
cont = 0;
MST(head,-1);
}
bool vis[MaxN];
int dis[MaxN];
void BFS(int s)
{
int cnt = 1;
int n = N; //n赋值为图中点数
int k, p, V;
queue<int> q;
CLR(vis);
for(int i=1;i<=n;i++)
dis[i] = INF;
q.push(s);
vis[s] = 1;
dis[s] = 0;
while(!q.empty())
{
k = q.front();
q.pop();
for(p = head[k]; p!=-1; p = edge[p].next)
{
V = edge[p].v;
if(vis[V]) continue;
dis[V] = k;
}
for(int i=1;i<=N;i++)
{
if(dis[i] == k || vis[i]) continue;
dis[i] = dis[k] + 1;
vis[i] = 1;
q.push(i);
cnt++;
if(cnt == N) return;
}
}
}
int main()
{
scanf("%d", &T);
while(T--)
{
init();
scanf("%d%d", &N, &M);
int u,v;
for(int i=0;i<M;i++)
{
scanf("%d%d", &u, &v);
Add(u,v);
}
int S;
scanf("%d", &S);
BFS(S);
bool flag = true;
for (int i = 1; i <= N; i++)
{
if (i == S) continue;
if (flag == false) printf(" ");
flag = false;
if (dis[i] == INF) printf("-1");
else printf("%d", dis[i]);
}
printf("\n");
}
//system("pause");
}