2351: 【入门】邻接点(2080)

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:5 解决:4

题目描述

一个有向图中有 lns="http://www.w3.org/1998/Math/MathML"> 个点(编号为 lns="http://www.w3.org/1998/Math/MathML">1 ),lns="http://www.w3.org/1998/Math/MathML"> 条边,请读入 lns="http://www.w3.org/1998/Math/MathML"> 条边,按照结点编号从小到大的顺序,输出每个点,及每个点的邻接点(有路径可到达的结点)有哪些(输出邻接点也按照编号从小到大的顺序)。

例如:有如下图所示的有向图

结点 lns="http://www.w3.org/1998/Math/MathML">1 的邻接点有:lns="http://www.w3.org/1998/Math/MathML">2 lns="http://www.w3.org/1998/Math/MathML">3 lns="http://www.w3.org/1998/Math/MathML">4

结点 lns="http://www.w3.org/1998/Math/MathML">2 的邻接点有:lns="http://www.w3.org/1998/Math/MathML">3 lns="http://www.w3.org/1998/Math/MathML">4

结点 lns="http://www.w3.org/1998/Math/MathML">3 的邻接点有:lns="http://www.w3.org/1998/Math/MathML">5

结点 lns="http://www.w3.org/1998/Math/MathML">4 的邻接点有:lns="http://www.w3.org/1998/Math/MathML">3 lns="http://www.w3.org/1998/Math/MathML">5

结点 lns="http://www.w3.org/1998/Math/MathML">5 没有邻接点。

输入

第 lns="http://www.w3.org/1998/Math/MathML">1 行有 lns="http://www.w3.org/1998/Math/MathML">2 个整数,lns="http://www.w3.org/1998/Math/MathML"> 和 lns="http://www.w3.org/1998/Math/MathML"> ,代表有 lns="http://www.w3.org/1998/Math/MathML"> 个点, lns="http://www.w3.org/1998/Math/MathML"> 条边;(lns="http://www.w3.org/1998/Math/MathML">1,000,000lns="http://www.w3.org/1998/Math/MathML">10,000);

接下来 lns="http://www.w3.org/1998/Math/MathML"> 行,每行有 lns="http://www.w3.org/1998/Math/MathML">2 个整数 lns="http://www.w3.org/1998/Math/MathML">, ,代表 lns="http://www.w3.org/1998/Math/MathML"> 到 lns="http://www.w3.org/1998/Math/MathML"> 之间存在一有向条边(lns="http://www.w3.org/1998/Math/MathML">,

本题测试数据确保任意两点之间最多只有 lns="http://www.w3.org/1998/Math/MathML">1 条边、且数据合法,不存在 lns="http://www.w3.org/1998/Math/MathML"> 点到 lns="http://www.w3.org/1998/Math/MathML"> 点有边的情况。

输出

按照从小到大的顺序,先输出每个点的编号(如果该点没有出度,则该点不输出),再换行输出该点有出边可达的点的编号(也是按从小到大的顺序),输出格式请参考本题的样例。

样例输入 复制

5 8
1 2
2 3
2 4
1 3
1 4
4 3
3 5
4 5

样例输出 复制

1
2 3 4
2
3 4
3
5
4
3 5

提示

样例解释:

样例输入将形成如下图所示的图形,其中:

结点1的邻接点有:2 3 4

结点2的邻接点有:3 4

结点3的邻接点有:5

结点4的邻接点有:3 5

结点5没有邻接点,因此不输出



#include<bits/stdc++.h>
using namespace std;
#define MAXN 1000010
int n,e;
vector <int> p[MAXN];
int main(){
    cin >> n >> e;
    for (int i = 1; i <= e ; i++) {
    	int u,v;
    	cin >> u >> v;
    	p[ u ].push_back(v);
	}
	for (int i = 1; i <= n ; i++) {
		if (p[i].size()) {
			cout << i << endl;
			sort(p[i].begin(),p[i].end());
		    for (int j = 0, sz = p[i].size(); j < sz ; j++) {
			    cout << p[i][j] << " "; 
		    }
			cout << endl;			
		} 

	}
	return 0;
}