链接:戳这里
Sparse Graph
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
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.
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
题意:
n个点m条边的图,给定一个点S,要求输出再补图上,S到所有点的最短路径
思路:
找出独立的点X(没有边连),那么S到X的距离为1,到其他的所有在图上的点距离为2
如果不存在独立的点,那么图很小,二维数组存边跑dijkstra
代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int vis[200100];
int n,m,S,X;
int anw[200100];
int u[20010],v[20010];
vector <int> V;
int a[10010][10010];
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) vis[i]=0;
for(int i=1;i<=n;i++) anw[i]=0;
V.clear();
for(int i=1;i<=m;i++) scanf("%d%d",&u[i],&v[i]);
scanf("%d",&S);
for(int i=1;i<=m;i++){
vis[u[i]]=vis[v[i]]=1;
if(u[i]==S) V.push_back(v[i]);
else if(v[i]==S) V.push_back(u[i]);
}
X=-1;
for(int i=1;i<=n;i++){
if(i!=S && !vis[i]) {
X=i;
break;
}
}
if(X!=-1){
int cnt=V.size();
for(int i=0;i<cnt;i++) anw[V[i]]=2;
for(int i=1;i<=n;i++) {
if(!anw[i]) anw[i]=1;
}
anw[S]=0;
} else {
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) a[i][j]=0;
else a[i][j]=a[j][i]=1;
}
}
for(int i=1;i<=m;i++){
a[u[i]][v[i]]=1e9;
a[v[i]][u[i]]=1e9;
}
for(int i=1;i<=n;i++) vis[i]=0;
for(int i=1;i<=n;i++) anw[i]=1e9;
anw[S]=0;
int flag=0;
for(int i=1;i<n;i++){
int f=-1,mn=1e9;
for(int j=1;j<=n;j++){
if(!vis[j] && anw[j]<mn){
f=j;
mn=anw[j];
}
}
if(f==-1){
flag=1;
break;
}
vis[f]=1;
for(int j=1;j<=n;j++){
if(!vis[j] && anw[f]+a[f][j]<anw[j]){
anw[j]=anw[f]+a[f][j];
}
}
}
if(flag){
printf("-1\n");
continue;
}
}
if(S==1) {
for(int i=2;i<n;i++) printf("%d ",anw[i]);
printf("%d\n",anw[n]);
} else {
printf("%d",anw[1]);
for(int i=2;i<=n;i++){
if(anw[i]) printf(" %d",anw[i]);
}
printf("\n");
}
}
return 0;
}
/*
10
4 3
1 2
2 3
3 4
2
*/