【发布时间】:2021-08-02 23:59:32
【问题描述】:
我正在解决一个图形问题,我必须从文件中获取输入。下面是我的 input.txt 文件。
12
1 2
2 3
2 4
2 5
3 6
4 5
4 7
5 2
5 6
5 7
6 3
6 8
7 8
7 10
8 7
9 7
10 9
10 11
11 12
12 10
在上面的 input.txt 文件中,第一个输入是没有顶点,直到文件末尾的其他输入是 Graph 的有向边。第一个是源,第二个是目标。所有输入将从 input.txt 文件中读取。
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
class Graph {
private:
int V;
list<int> *l;
public:
Graph(int V) {
this->V = V;
l = new list<int>[V];
}
void addEdge(int source, int destination) {
// As it is a directed graph edge will be source to destination only
l[source].push_back(destination);
}
void printAdjList() {
for(int i = 1; i <= V; i++) {
cout << "Vertex " << i << "-> " ;
for(int previous: l[i]) {
cout << previous << " " ;
}
cout << endl;
}
}
};
int main() {
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
ifstream inputFile;
inputFile.open("input.txt");
int noOfVertex, s, d, noOfEdge=20;
inputFile >> noOfVertex ;
// cout << noOfVertex << endl;
Graph g(noOfEdge);
// while(cin.eof()) {
// // cout << s << " " << d << endl;
// cin >> s >> d;
// g.addEdge(s, d);
// }
if(inputFile) {
while(inputFile >> s >> d) {
// cout << s << " " << d << endl;
g.addEdge(s, d);
}
inputFile.close();
}
else {
cout << "Error opening input file" << endl;
}
g.printAdjList();
return 0;
}
运行代码后我得到了这个结果
Vertex 1-> 2
Vertex 2-> 3 4 5
Vertex 3-> 6
Vertex 4-> 5 7
Vertex 5-> 2 6 7
Vertex 6-> 3 8
Vertex 7-> 8 10
Vertex 8-> 7
Vertex 9-> 7
Vertex 10-> 9 11
Vertex 11-> 12
Vertex 12-> 10
Vertex 13->
Vertex 14->
Vertex 15->
Vertex 16->
Vertex 17->
Vertex 18->
Vertex 19->
我不能为这个问题取边数。 vetices 的数量和给定的有向边将从文件中逐行获取,并显示类似的邻接列表
Vertex 1-> 2
Vertex 2-> 3 4 5
Vertex 3-> 6
Vertex 4-> 5 7
Vertex 5-> 2 6 7
Vertex 6-> 3 8
Vertex 7-> 8 10
Vertex 8-> 7
Vertex 9-> 7
Vertex 10-> 9 11
Vertex 11-> 12
Vertex 12-> 10
如何从文件中获取输入,以便获得上述输出?我已经应用了很多方法,但没有任何效果。
【问题讨论】:
-
您的 Graph 构造函数将多个节点作为参数。你为什么要传递边数?
-
Unrelated:
#include <fstream>暗示你不知道#include <bits/stdc++.h>做了什么。这里有一些关于它的阅读以及一个不太微妙的建议:Why should I not #include <bits/stdc++.h>? -
硬编码
noOfEdge只会带来痛苦和折磨。幸运的是,它没有任何用处,您可以将其删除。 -
与您的问题没有直接关系,但您知道数组索引在 C 语言中从 0 开始吗?
标签: c++ algorithm input graph eof