1057.树的查询
Time Limit: 1000 MS Memory Limit: 32768 KB
Total Submission(s): 367 Accepted Submission(s): 65
Description
给定 n(1 <= n <= 1000000), m(1 <= m <= 10) 分别表示一棵树中节点的个数及查询的数量,每个节点的编号为给定的顺序,之后给定每个节点的父节点编号,及 m 个查询,每个查询中,给定一个节点编号,对于每个查询,按编号从小到大输出该节点所有子节点。
Input
第一行两个整数n, m,之后n行,每行两个整数a, b,表示编号为a的节点的父节点是b,b为0表示没有父节点,数据保证编号为1至n的节点均在a位置出现一次,之后一行m个整数,表示每个查询要查询的节点编号。
Output
m行,每行若干个从小到大排好序的、用一个空格隔开的整数,表示该次查询的节点的所有子节点。
Sample Input
5 1
1 0
4 1
2 1
5 1
3 1
1
Sample Output
2 3 4 5
Source
Unknown
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int h[1000000];
map<int ,vector<int> > mp;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
while(n--)
{
scanf("%d%d",&a,&b);
mp[b].push_back(a);
}
while(m--)
{
int f;
int i;
scanf("%d",&f);
for( i=0;i<mp[f].size();i++)
{
h[i]=mp[f][i];
}
sort(h,h+i);
for(int j=0;j<i;j++)
{
cout<<h[j];
if(j!=i-1)
cout<<' ';
}
cout<<'\n';
}
return 0;
}