【发布时间】:2016-06-17 06:16:24
【问题描述】:
我编写了一个简单的代码来获取顶点数和边数作为输入,获取每条边并将其添加到该顶点的列表中。但是,我没有做对。
#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
【问题讨论】:
标签: graph-theory breadth-first-search adjacency-list