Sparse Graph
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 617 Accepted Submission(s): 210
Problem Description
In graph theory, the
complement
of a graph G
is a graph H
on the same vertices such that two distinct vertices of
H
are adjacent if and only if they are not
adjacent in G.
Now you are given an undirected graph G of N nodes and M bidirectional edges of unit length. Consider the complement of G, i.e., H. For a given vertex S on H, you are required to compute the shortest distances from S to all N−1 other vertices.
Now you are given an undirected graph G of N nodes and M bidirectional edges of unit length. Consider the complement of G, i.e., H. For a given vertex S on H, you are required to compute the shortest distances from S to all N−1 other vertices.
Input
There are multiple test cases. The first line of input is an integer
T(1≤T<35)
denoting the number of test cases. For each test case, the first line contains two integers
N(2≤N≤200000)
and M(0≤M≤20000).
The following M
lines each contains two distinct integers u,v(1≤u,v≤N)
denoting an edge. And S (1≤S≤N)
is given on the last line.
Output
For each of
T
test cases, print a single line consisting of N−1
space separated integers, denoting shortest distances of the remaining
N−1
vertices from S
(if a vertex cannot be reached from S, output ``-1" (without quotes) instead) in ascending order of vertex number.
Sample Input
1 2 0 1
Sample Output
1 题意:给你一个图,和一个点s,然后问在它的补图中,点s到每个点的最短路是多长。 解题思路: 题意不难,但是第一次在树上做BFS,感觉边的关系不好维护,比赛时想到一个想法,但是不敢想,赛后写出来了。 给每个点开一个vector,然后记录跟这个点直接连接的点。然后以s为起点进行bfs.<span style="font-size:18px;"> #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<set> #include<queue> using namespace std; const int maxn=200010; vector<int> v[maxn]; int n,m,dis[maxn],s; void BFS() { set<int> s1,s2; set<int>::iterator it; queue<int> que; que.push(s); dis[s]=0; for(int i=1;i<=n;i++) if(i!=s) s1.insert(i); while(!que.empty()) { int u=que.front(); que.pop(); int len=v[u].size(); for(int i=0;i<len;i++) { int vv=v[u][i]; if(!s1.count(vv)) continue; s1.erase(vv); s2.insert(vv); } for(it=s1.begin();it!=s1.end();it++) { que.push(*it); dis[*it]=dis[u]+1; } s1.swap(s2); s2.clear(); } } int main() { int t,a,b; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); memset(dis,0x3f,sizeof(dis)); for(int i=0;i<maxn;i++) v[i].clear(); for(int i=0;i<m;i++) { scanf("%d %d",&a,&b); v[a].push_back(b); v[b].push_back(a); } scanf("%d",&s); BFS(); for(int i=1;i<=n;i++) { if(i==s){ if(i==n) printf("\n"); continue; } printf("%d%c",dis[i],i==n? '\n' : ' '); } } return 0; } </span>