【问题标题】:Graph adjacency list giving wrong output图形邻接列表给出错误的输出
【发布时间】: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


    【解决方案1】:

    知道了。

    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2020-12-18
      相关资源
      最近更新 更多