FIG hoop has sentenced

Programming such a face questions, to a directed graph adjacency matrix, determines whether it has a ring.

Title trouble is given adjacency matrix 'character input stream' is given in the form, so its form is processed into digital work to be done first.

After obtaining the adjacency matrix can be topologically sorted. If it is not able to complete topological sorting ring, if not, that is, there are rings.

Sample input:

[[0, 1, 0], [0, 0, 1], [1, 0, 0]]

[[0, 0, 0, 1, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0]]

Output: (1 represents a cycloalkyl, 0 represents no ring)

1

0

 

 1 #include <bits/stdc++.h> 
 2 using namespace std; 
 3 
 4 int str2int(string str){
 5     for(int i=0; i<str.size(); i++){
 6         if(str[i]=='0') return 0;
 7         if(str[i]=='1') return 1;
 8     }
 9     return -1;
10 }
11 
12 int main(int argc, char const *argv[]){
13     string str;
14     while(getline(cin, str) ){
15         istringstream temp(str);
16         str.clear();
17         
18         string cur;
19         vector<string> data;
20         while(temp>>cur ){
21             data.push_back(cur );
22             cur.clear();
23         }
24         
25         int= sqrt n-(data.size ());                       // n-number of nodes is 
26 is          Vector <Vector < int >> Graph (n-, Vector < int > (n-, 0 ));    // adjacency matrix 
27          
28          for ( int I = 0 ; I <n-; I ++ ) {
 29              for ( int J = 0 ; J <n-; J ++ ) { 
 30                  Graph [I] [J] = str2int (Data [n-* I + J]);
 31 is              } 
 32          }
 33 is          
34 is          Vector < int > visited (n-, 0);     // n-is the number of nodes, obtained from the treated above 
35          Vector < int > indegree (n-, 0 );    // the degree of each node 
36          for ( int I = 0 ; I <n-; I ++ ) {
 37 [              for ( int J = 0 ; J <n-; J ++ ) {
 38 is                  IF (Graph [I] [J] == . 1 ) {
 39                      indegree [J] ++ ;
 40                  }                
 41 is              }
 42 is          } 
 43 is          Queue < int > q;
44         for(int i=0;i<n;i++){
45             if(indegree[i]==0) 
46                 q.push(i);
47         }
48         
49         int now;
50         while(!q.empty()){
51             now = q.front();
52             q.pop();
53             visited[now] = 1;
54             for(int i=0;i<n;i++){
55                 if(!visited[i] && graph[now][i]==1){
56                     indegree[i]--;
57                     if(indegree[i]==0) q.push(i); 
58                 }
59             }
60         }
61         
62         bool sign = 0;
63         for(int i=0; i<n; i++){
64             if(!visited[i]){
65                 sign = 1;
66                 break;
67             }            
68         }
69         
70         cout<<sign<<endl;
71     } 
72     
73     
74     return 0;
75 }

 

Guess you like

Origin www.cnblogs.com/liugl7/p/11272614.html