【HDU - 5876】Sparse Graph(补图bfs,STLset)
題干:
In graph theory, the?complementcomplement?of a graph?GG?is a graph?HH?on the same vertices such that two distinct vertices of?HH?are adjacent if and only if they are?notnotadjacent in?GG.?
Now you are given an undirected graph?GG?of?NN?nodes and?MM?bidirectional edges of?unitunit?length. Consider the complement of?GG, i.e.,?HH. For a given vertex?SS?on?HH, you are required to compute the shortest distances from?SS?to all?N?1N?1?other vertices.
Input
There are multiple test cases. The first line of input is an integer?T(1≤T<35)T(1≤T<35)denoting the number of test cases. For each test case, the first line contains two integers?N(2≤N≤200000)N(2≤N≤200000)?and?M(0≤M≤20000)M(0≤M≤20000). The following?MM?lines each contains two distinct integers?u,v(1≤u,v≤N)u,v(1≤u,v≤N)?denoting an edge. And?S?(1≤S≤N)S?(1≤S≤N)is given on the last line.
Output
For each of?TT?test cases, print a single line consisting of?N?1N?1?space separated integers, denoting shortest distances of the remaining?N?1N?1?vertices from?SS?(if a vertex cannot be reached from S, output ``-1" (without quotes) instead) in ascending order of vertex number.
Sample Input
1 2 0 1Sample Output
1題目大意:
給一個N個點M條邊的無向圖,給你一個圓點,讓你在對應圖的補圖上求出起點S到每個點的最短路。
解題報告:
正常bfs是對于當前點來說枚舉當前點的每一條邊,看該點是否遍歷過來決定是否進行入隊操作。而對于這個題,因為補圖的邊的數量非常大,所以我們可以從點的角度入手,因為一共需要更新1e5個點,所以我們可以直接在每一次循環中都先枚舉每一個點,看他和當前點是否有連邊,如果原圖中沒有這條邊的話那就可以直接更新這個點,并且把他放到隊列中。通過枚舉邊變成枚舉點,減少時間復雜度。也就是正常bfs是枚舉每一個邊看是否出點被更新過,這個題因為邊數很多但是點數不多,所以可以枚舉每一個沒出現過的點,看這條邊是否存在。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int INF = 0x3f3f3f3f; const int MAX = 2e5 + 5; set<int> ss; set<int> vv[MAX]; int st,n,m; int dis[MAX]; void bfs(int st) {for(int i = 1; i<=n; i++) dis[i] = INF;dis[st] = 0;ss.erase(st);queue<int> q;q.push(st);while(q.size()) {vector<int> tmp;int cur = q.front();q.pop();for(auto it = ss.begin();it!=ss.end(); ++it) {int v = *it;if(vv[cur].find(v) == vv[cur].end()) {dis[v] = dis[cur]+1;tmp.pb(v); q.push(v);} }for(auto v : tmp) ss.erase(v);} } int main() {int T;cin>>T;while(T--) {scanf("%d%d",&n,&m);ss.clear();for(int i = 1; i<=n; i++) ss.insert(i);for(int i = 1; i<=n; i++) vv[i].clear();for(int u,v,i = 1; i<=m; i++) scanf("%d%d",&u,&v),vv[u].insert(v),vv[v].insert(u);scanf("%d",&st);bfs(st);int cnt = 1;for(int i = 1; i<=n; i++) {if(i == st) continue;if(dis[i] == INF) printf("%d%c",-1,cnt == n-1 ? '\n' :' ') ;else printf("%d%c",dis[i],cnt == n-1 ? '\n' :' ');cnt++;}}return 0 ; }?
總結
以上是生活随笔為你收集整理的【HDU - 5876】Sparse Graph(补图bfs,STLset)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 神秘的太阳系第九行星:几乎肯定存在 等于
- 下一篇: 【牛客 - 551F】CSL 的神奇序列