天天看點

TOJ 3365 It's not Floyd Algorithm -- 強連通分量 + floyd

參考:

http://blog.csdn.net/mfmy_szw/article/details/18740453

另一個不同做法:blog點sina.com.cn/s/blog_6a44b3340100ko9d.html

代碼:

#include 
   
    
#include 
    
     
#include 
     
      
#include 
      
       
#include 
       
         #include 
         #include 
         
           #include 
          
            #include 
           
             #include 
            
              #include 
             
               #include 
              
                #include 
               
                 #include 
                
                  #include 
                 
                   #include 
                  
                    #define mp make_pair #define X first #define Y second #define MEMSET(a, b) memset(a, b, sizeof(a)) using namespace std; typedef unsigned int ui; typedef long long ll; typedef unsigned long long ull; typedef pair
                   
                     pii; typedef vector
                    
                      vi; typedef vi::iterator vi_it; typedef map
                     
                       mii; typedef priority_queue
                      
                        pqi; typedef priority_queue
                       
                        , greater
                        
                          > rpqi; typedef priority_queue
                         
                           pqp; typedef priority_queue
                          
                           , greater
                           
                             > rpqp; const int MAX_N = 200 + 2; int dfn[MAX_N], low[MAX_N], scc[MAX_N], stk[MAX_N]; int num[MAX_N]; int cnt, idx, top; bool matrix[MAX_N][MAX_N]; bool new_map[MAX_N][MAX_N]; int n; void dfs(int u) { dfn[u] = low[u] = ++idx; stk[top++] = u; for (int i = 0; i < n; ++i) { if (i == u || !matrix[u][i]) continue; if (!dfn[i]) { dfs(i); low[u] = min(low[u], low[i]); } else if (!scc[i]) low[u] = min(low[u], dfn[i]); } if (dfn[u] == low[u]) { ++num[scc[u] = ++cnt]; while (stk[--top] != u) ++num[scc[stk[top]] = cnt]; } } void tarjan() { MEMSET(dfn, 0); MEMSET(scc, 0); MEMSET(num, 0); top = idx = cnt = 0; for (int i = 0; i < n; ++i) { if (!dfn[i]) dfs(i); } } void floyd() { for (int k = 1; k <= cnt; ++k) { for (int i = 1; i <= cnt; ++i) { if (!new_map[i][k]) continue; for (int j = 1; j <= cnt; ++j) { if (new_map[k][j]) new_map[i][j] = false; } } } } int main(int argc, char *argv[]) { // freopen("D:\\in.txt", "r", stdin); int i, j; while (cin >> n) { for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { int tmp; scanf("%d", &tmp); matrix[i][j] = tmp; } } tarjan(); int ans = 0; for (i = 1; i <= cnt; ++i) { if (num[i] > 1) ans += num[i]; } MEMSET(new_map, 0); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if (i != j && matrix[i][j]) new_map[scc[i]][scc[j]] = true; } } floyd(); for (i = 1; i <= cnt; ++i) { for (j = 1; j <= cnt; ++j) { if (i != j && new_map[i][j]) ++ans; } } cout << ans << endl; } return 0; }