题目
无向图,共有10个点,输入m条边。
输入:
10
1 2
2 4
3 4
5 6
7 9
10 1
8 9
9 5
3 7
3 8
输出:
1 : 2 10
2 : 1 4
3 : 4 7 8
4 : 2 3
5 : 6 9
6 : 5
7 : 9 3
8 : 9 3
9 : 7 8 5
10 : 1
代码:
#include <iostream>
#include<vector>
using namespace std;
int main() {vector<int>G[11];int m;cin>>m;for(int i=0;i<m;++i){int a,b;cin>>a>>b;G[a].push_back(b);G[b].push_back(a);}for(int i=1;i<=10;i++){cout<<i<<" : ";for(int j=0;j<G[i].size();j++){cout<<G[i][j]<<" ";}cout<<endl;}return 0;
}
题目:
带权图
10
1 2 3
2 4 4
3 4 2
5 6 1
7 9 0
10 1 -7
8 9 -4
9 5 10
3 7 11
3 8 20
输出:
(1, 2, 3)
(1, 10, -7)
(2, 1, 3)
(2, 4, 4)
(3, 4, 2)
(3, 7, 11)
(3, 8, 20)
(4, 2, 4)
(4, 3, 2)
(5, 6, 1)
(5, 9, 10)
(6, 5, 1)
(7, 9, 0)
(7, 3, 11)
(8, 9, -4)
(8, 3, 20)
(9, 7, 0)
(9, 8, -4)
(9, 5, 10)
(10, 1, -7)
代码:
#include <iostream>
#include <vector>
using namespace std;
struct node{int v,w;
};
vector<node> G[11];
void insert1(int u,int v,int w){node temp;temp.v=v;temp.w=w;G[u].push_back(temp);
}
void insert2(int u,int v,int w){insert1(u,v,w);insert1(v,u,w);
}
void input(){int m;cin>>m;for(int i=0;i<m;++i){int u,v,w;cin>>u>>v>>w;insert2(u,v,w);}
}
void output()
{for(int i=1;i<=10;++i){for(int j=0;j<G[i].size();j++){cout<<"("<<i<<", "<<G[i][j].v<<", "<<G[i][j].w<<")"<<endl;}}
}
int main() {input();output();return 0;
}
链表实现
const int M = 1000000;
const int N = 10000;
struct edge {int v, d, next;
} e[M];
int p[N], eid;
void init() { // 初始化,在建图之前必须进行memset(p, -1, sizeof(p));eid = 0;
}
void insert(int u, int v, int d) { // 插入单向边e[eid].v = v;e[eid].d = d;e[eid].next = p[u];p[u] = eid++;
}
void insert2(int u, int v, int d) { // 插入双向边insert(u, v, d);insert(v, u, d);
}
void output(int n) { // 输出整张图中的所有边for (int i = 0; i < n; i++) {for (int j = p[i]; j != -1; j = e[j].next) { // 遍历从 i 连出的所有边cout << i << "->" << e[j].v << ", " << e[j].d << endl;}}
}