如何在不使用 C++ 标准库的情况下以特定格式打印相邻列表?
How do I print adjacent list in specific format without using the C++ standard library?
我有一个无向加权图:
我想按以下格式打印相邻列表:
0--> 1 --> 2
1 --> 0 --> 2 --> 3
2 --> 0 --> 1 --> 4
3 --> 1 --> 4
4 --> 2 --> 3 --> 5
5 --> 4 --> 6
6-->5
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int nodes = 7;
int graphList[nodes][nodes];
for(int i = 0; i<nodes;i++){
for(int j = 0; j<nodes;j++){
graphList[i][j]=0;
}
}
int n1, n2, weight;
for(int j = 0; j<8;j++){
cin>>n1>>n2>>weight;
graphList[n1][n2]= weight;
graphList[n2][n1]= weight;
}
cout<<"Adjacent list: \n";
for(int i = 0; i<nodes;i++){
for(int j = 0; j<nodes;j++){
if(graphList[i][j]!=0){
cout<<i<<"-->"<<j<<endl;
}
}
}
return 0;
}
这样我就能得到这样的输出:
Adjacent list:
0-->1
0-->2
1-->0
1-->2
1-->3
2-->0
2-->1
2-->4
3-->1
3-->4
4-->2
4-->3
4-->5
5-->4
5-->6
6-->5
如何在不使用 C++ 标准库的情况下按上述格式进行打印?
注意:这是一个作业,所以我不能使用标准库作为要求。
由于您可以按第一个元素的字母顺序输出邻接列表,因此您可以简单地输出您想要的格式,并在 :
的内部循环中使用一个标志
cout<<"Adjacent list: \n";
for(int i = 0; i<nodes;i++){
bool flag = true;
for(int j = 0; j<nodes;j++){
if(graphList[i][j]!=0){
if (flag) {
cout<<i<<"-->"<<j;
flag = false;
}
else {
cout<<"-->"<<j;
}
}
}
cout<<endl;
}
在if语句中,如果first在里面,则输出第一个元素otherweise,输出"-->"第二个元素。
我有一个无向加权图:
我想按以下格式打印相邻列表:
0--> 1 --> 2
1 --> 0 --> 2 --> 3
2 --> 0 --> 1 --> 4
3 --> 1 --> 4
4 --> 2 --> 3 --> 5
5 --> 4 --> 6
6-->5
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int nodes = 7;
int graphList[nodes][nodes];
for(int i = 0; i<nodes;i++){
for(int j = 0; j<nodes;j++){
graphList[i][j]=0;
}
}
int n1, n2, weight;
for(int j = 0; j<8;j++){
cin>>n1>>n2>>weight;
graphList[n1][n2]= weight;
graphList[n2][n1]= weight;
}
cout<<"Adjacent list: \n";
for(int i = 0; i<nodes;i++){
for(int j = 0; j<nodes;j++){
if(graphList[i][j]!=0){
cout<<i<<"-->"<<j<<endl;
}
}
}
return 0;
}
这样我就能得到这样的输出:
Adjacent list:
0-->1
0-->2
1-->0
1-->2
1-->3
2-->0
2-->1
2-->4
3-->1
3-->4
4-->2
4-->3
4-->5
5-->4
5-->6
6-->5
如何在不使用 C++ 标准库的情况下按上述格式进行打印?
注意:这是一个作业,所以我不能使用标准库作为要求。
由于您可以按第一个元素的字母顺序输出邻接列表,因此您可以简单地输出您想要的格式,并在 :
的内部循环中使用一个标志 cout<<"Adjacent list: \n";
for(int i = 0; i<nodes;i++){
bool flag = true;
for(int j = 0; j<nodes;j++){
if(graphList[i][j]!=0){
if (flag) {
cout<<i<<"-->"<<j;
flag = false;
}
else {
cout<<"-->"<<j;
}
}
}
cout<<endl;
}
在if语句中,如果first在里面,则输出第一个元素otherweise,输出"-->"第二个元素。