- 时间:200ms
- 内存:131072K
Bananas are the favoured food of monkeys.
In the forest, there is a Banana Company that provides bananas from different places.
The company has two lists.
The first list records the types of bananas preferred by different monkeys, and the second one records the types of bananas from different places.
Now, the supplier wants to know, whether a monkey can accept at least one type of bananas from a place.
Remenber that, there could be more than one types of bananas from a place, and there also could be more than one types of bananas of a monkey's preference.
Input Format
The first line contains an integer T, indicating that there are T test cases.
For each test case, the first line contains two integers N and M, representing the length of the first and the second lists respectively.
In the each line of following N lines, two positive integers i,j indicate that the i-th monkey favours the j-th type of banana.
In the each line of following M lines, two positive integers j,k indicate that the j-th type of banana could be find in the k-th place.
All integers of the input are less than or equal to 50.
Output Format
For each test case, output all the pairs x,y that the x-the monkey can accept at least one type of bananas from the y-th place.
These pairs should be outputted as ascending order. That is say that a pair of x,y which owns a smaller xshould be output first.
If two pairs own the same x, output the one who has a smaller y first.
And there should be an empty line after each test case.
样例输入
1
6 4
1 1
1 2
2 1
2 3
3 3
4 1
1 1
1 3
2 2
3 3
样例输出
1 1
1 2
1 3
2 1
2 3
3 3
4 1
4 3
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
int main()
{
int t,n,m,a,b;
scanf("%d",&t);
while(t--)
{
int max1=-1,pre[55];
vector<int> s[55],h[55];
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%d %d",&a,&b);
s[a].push_back(b);//统计 a 种猴子喜欢的香蕉种类
if(max1<a)//记录最大编号的猴子,避免后面不必要的循环次数
max1=a;
}
for(int i=0;i<m;i++)
{
scanf("%d %d",&a,&b);
h[a].push_back(b);//统计 i 种香蕉的种植地
}
for(int i=0; i<=max1; i++)
{
int k=0;
memset(pre,-1,sizeof(pre));
if(s[i].size()!=0)//如果有此类猴子喜欢的香蕉存在
{
for(int j=0; j<s[i].size(); j++)//搜索此类香蕉的种植地
{
int temp=s[i][j];
for(int l=0; l<h[temp].size(); l++)
{
pre[k++]=h[temp][l];//将一类猴子喜欢的所有种类香蕉的种植地都存入到pre数组
}
}
sort(pre,pre+k);//对pre数组排序
for(int l=0;l<k;l++)//对pre数组去重,避免输出重复的种植地
if(pre[l]!=pre[l+1])
printf("%d %d\n",i,pre[l]);
}
}
printf("\n");
}
return 0;
}