朱色虫居
Pages
Home
Featured Posts
2007/02/12
459-Graph Connectivity
/*
"Graph Connectivity"
Level:5.0
Date:2007/2/11
技巧:
先建立adjacency matrix,
再用DFS traversal找sub graph的數目.
題目的input data可能是夾雜空白的,所以需要對input data filter掉多餘的空白,
read.erase(remove(read.begin(), read.end(), ' '), read.end());
上面這招很好用,多謝強哥教我....orz..
*/
#include
#include
#include
using namespace std;
int ans, size;
bool visited[26], table[26][26];
void DFS(int node){
visited[node] = true;
for(int i=0;i < size;++i){ if(table[node][i] == true && visited[i] == false) DFS(i); } } int main(){ int turn, n1, n2; string c; string read; cin>>turn;
while(turn--){
ans = 0;
cin>>c;
cin.ignore(); //清除stream裡的多餘字完('\n')
size = c[0] - 'A'+1;
for(int i=0; i < 26; ++i) for(int j=0; j < 26; ++j) table[i][j] = false; while(1){ //建立adjcent matrix. getline(cin, read); read.erase(remove(read.begin(), read.end(), ' '), read.end()); //filter掉多餘空白. if( read.empty() == true) break; n1 = read[0] - 'A'; n2 = read[1] - 'A'; table[n1][n2] = true; table[n2][n1] = true; } for(int i=0; i < size; ++i){ if(visited[i] == false){ DFS(i); ++ans; } } cout<< ans << endl; if(turn != 0) cout << endl; for(int i=0;i < size;++i) visited[i]= false; } return 0; }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment