2016-06-17 15 views
0

私は、頂点の数と辺の数を入力として単純なコードを作り、各辺を取り出し、その頂点のリストに追加します。しかし、私はそれを正しくしていません。グラフの隣接リストが間違った出力を返す

#include <iostream> 
#include <list> 

using namespace std; 

int main() 
{ 
    int t; 
    cin>>t; 
    while(t--) { 
     int n,m; // number of vertices and edges 
     cin>>n>>m; 
     list<int> a[n]; 
     list<int>::iterator it; 
     while(m--) { 
      int x,y; 
      cin>>x>>y; // one edge x & y are vertices 
      a[x-1].push_back(y-1); // -1 because it array is 0 index based 
     } 
     for(int i=0;i<n;i++) { 
      for(it= a[i].begin();it!=a[i].end();it++) { 
       cout<<*it<<" "; 
      } 
      cout<<endl; 
     } 
    } 
    return 0; 
} 

は私の入力テストケースがあるとしましょう:

1 
3 3 // number of edges and vertices 
1 2 
2 3 
3 1 

の予想される出力は次のようになります。

2 3 
1 2 
2 1 

答えて

0

はそれを手に入れました。

#include <iostream> 
#include <list> 

using namespace std; 

int main() 
{ 
    int t; 
    cin>>t; 
    while(t--) { 
     int n,m; 
     cin>>n>>m; 
     list<int> a[n]; 
     list<int>::iterator it; 
     while(m--) { 
      int x,y; 
      cin>>x>>y; 
      a[x-1].push_back(y); 
      a[y-1].push_back(x); 
     } 
     for(int i=0;i<n;i++) { 
      for(it= a[i].begin();it!=a[i].end();it++) { 
       cout<<*it<<" "; 
      } 
      cout<<endl; 
     } 
    } 
    return 0; 
} 
関連する問題