Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- In graph theoretic terms, b_ij > 0 in the matrix A^k means that there is a
- path of k steps from i to j. Now, because there is at least one non-zero
- on the diagonal, it means that node represents a cycle of length 1. So if
- the graph has one strong component then eventually with a high enough power
- you will e able to get from anywhere to anywhere in that number of steps.
- Also, if the graph is not strongly connected, then there will be some b_ij
- which always remain 0.
- So the property holds if and only if the graph has one big strong component.
- */
- // 1-based
- namespace SCC {
- vector<vector<int>> g, rg, scc, sccg;
- vector<int> nodes, vis, who;
- int comp, n;
- void init(int n_) {
- n = n_;
- g.assign(n+1,{});
- rg.assign(n+1,{});
- vis.assign(n+1,0);
- nodes.clear();
- who.assign(n+1,0);
- comp = 0;
- }
- void addEdge(int u, int v) {
- g[u].push_back(v);
- rg[v].push_back(u);
- }
- void dfs1(int u) {
- vis[u] = 1;
- for(int v : g[u]) {
- if(!vis[v]) dfs1(v);
- }
- nodes.push_back(u);
- }
- void dfs2(int u) {
- who[u] = comp;
- for(int v: rg[u]) {
- if (!who[v]) dfs2(v);
- }
- }
- void SCC() {
- for(int i = 1; i <= n; i++) {
- if(!vis[i]) dfs1(i);
- }
- reverse(nodes.begin(), nodes.end());
- for(int u: nodes) {
- if (!who[u]) {
- ++comp;
- dfs2(u);
- }
- }
- scc.assign(comp+1,{});
- for(int i = 1; i <= n; i++) {
- scc[who[i]].push_back(i);
- }
- sccg.assign(comp + 1,{});
- for(int u = 1; u <= n; u++) {
- for(int v : g[u]) {
- if (who[u] != who[v]) {
- sccg[who[u]].push_back(who[v]);
- }
- }
- }
- for(int i = 1; i <= comp; i++) {
- sort(sccg[i].begin(), sccg[i].end());
- sccg[i].erase(unique(sccg[i].begin(), sccg[i].end()), sccg[i].end());
- }
- }
- }
- int main() {
- booster()
- int n;
- cin >> n;
- SCC::init(n);
- for(int u = 1; u <= n; u++) {
- for(int v = 1; v <= n; v++) {
- int ej; cin >> ej;
- if(ej) SCC::addEdge(u, v);
- }
- }
- SCC::SCC();
- if(SCC::comp == 1) {
- cout << "YES";
- }
- else {
- cout << "NO";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement