PAT 1139

题目 : First Contact

分值 : 30
难度 : 内存题
思路 : 存个图,然后请求的两个人分别去看她们的好友 是否存在联系
坑点 : 内存超限制

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <math.h>
#include <unordered_map>
using namespace std;
unordered_map<int, bool> Map;
map <int,vector<int>> Tx ;
typedef struct Node
{
int a ;
int b ;
};
bool cmp(Node a , Node b)
{
if(a.a != b.a )
return a.a < b.a ;
return a.b < b.b ;
}
int main() {
int N ,M; cin >> N >>M ; // v[i][0] = 0 for girl v[i][0] = 1 for boy
int c1 , c2 ;
string s1 ,s2 ;
int count ;
for(int i = 0 ;i <M; i++)
{
count=0;
cin >>s1 >>s2 ;
if(s1[0] =='-')count ++;
if(s2[0] =='-')count ++;
c1 = atoi(s1.c_str()) ;
c2 = atoi(s2.c_str()) ;
Map[abs(c1)*10000+abs(c2)] = true ;
Map[abs(c2)*10000+abs(c1)] = true ;
if(count%2 ==0) // same gender friend
{
Tx[abs(c1)].push_back(abs(c2)) ;
Tx[abs(c2)].push_back(abs(c1)) ;
}
}
int K ;
cin>> K ;
for(int i = 0 ; i< K ;i++)
{
vector<Node> result;
int t1,t2;
cin >> c1 >>c2 ;
//cout <<c1 <<"====="<<c2 <<endl;
if(true){
for(int i = 0 ; i<Tx[abs(c1)].size(); i++)
{
t1 = Tx[abs(c1)][i] ;
if(t1 == abs(c2)) continue ;
for(int j = 0 ; j < Tx[abs(c2)].size() ; j++)
{
t2 = Tx[abs(c2)][j] ;
if(t2 == abs(c1)) continue ;
if(Map[t1*10000+t2])
{
Node temp ;
temp.a = t1 ;
temp.b = t2 ;
result.push_back(temp) ;
}
}
}
}
cout <<result.size()<<endl ;
sort(result.begin() , result.end(), cmp);
for(int i = 0 ; i< result.size(); i++)
{
printf("%04d %04d\n",result[i].a ,result[i].b) ;
}
}
}