PAT A1139 First Contact [图]
题目描述
链接
+A-->+C--->-D--->-B
+A--->+C--->+D--->+B
分析
- 最开始想的用图建立关系,其实没想错,但是有几个点没想到
- A在寻找同性朋友时,需要避免找到他想要的伴侣B,所以当当前朋友就是B或者B的同性朋友就是A时舍弃该结果
- 输出时候要以4位数的方式输出,所以要%04d
- 如果用int接收一对朋友,-0000和0000对于int来说都是0,将无法得知这个人的性别,也就会影响他找他的同性朋友的那个步骤
- 别人的方法是简化了一下:用数组re标记两个人是否是朋友(邻接矩阵表示),用v标记所有人的同性朋友(邻接表表示)
- stoi的使用!!!!!
- 用abs来统一正负号!!!不用写判断了!!!!!!!
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
struct node{
int id, gen;
};
vector<node> G[maxn];
int n,m,k;
string a,b;
bool cmp(pair<int, int> x, pair<int,int> y){
if(x.first != y.first) return x.first < y.first;
return x.second < y.second;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
cin>>a>>b;
node x,y;
if(a[0] == '-'){
x.id = stoi(a) * (-1);
x.gen = 0;
}else{
x.id = stoi(a);
x.gen = 1;
}
if(b[0] == '-'){
y.id = stoi(b) * (-1);
y.gen = 0;
}else{
y.id = stoi(b);
y.gen = 1;
}
G[x.id].push_back(y);
G[y.id].push_back(x);
}
scanf("%d",&k);
while(k--){
vector<pair<int,int> > ans;
cin>>a>>b;
node x,y;
if(a[0] == '-'){
x.id = stoi(a) * (-1);
x.gen = 0;
}else{
x.id = stoi(a);
x.gen = 1;
}
if(b[0] == '-'){
y.id = stoi(b) * (-1);
y.gen = 0;
}else{
y.id = stoi(b);
y.gen = 1;
}
int cnt = 0;
for(int i=0;i<G[x.id].size();i++){
if(G[x.id][i].gen != x.gen) continue;
if(G[x.id][i].id == y.id) continue;
for(int j=0;j<G[y.id].size();j++){
if(G[y.id][j].gen != y.gen) continue;
if(G[y.id][j].id == x.id) continue;
for(int k=0;k<G[G[x.id][i].id].size();k++){
if(G[G[x.id][i].id][k].id == G[y.id][j].id){
cnt++;
ans.push_back(make_pair(G[x.id][i].id, G[y.id][j].id));
}
}
}
}
sort(ans.begin(), ans.end(), cmp);
printf("%d\n",cnt);
for(int i=0;i<ans.size();i++){
printf("%04d %04d\n", ans[i].first, ans[i].second);
}
}
}
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
const int maxn = 10000; //提示!!N小于1000,用矩阵
bool re[maxn][maxn]; //标记是否有关系
vector<int> G[maxn]; //保存其同性
bool cmp(pair<int, int> x, pair<int,int> y){
if(x.first != y.first) return x.first < y.first;
return x.second < y.second;
}
int main(){
scanf("%d%d",&n,&m);
string a,b;
for(int i=0;i<m;i++){
cin>>a>>b;
re[abs(stoi(a))][abs(stoi(b))] = true;
re[abs(stoi(b))][abs(stoi(a))] = true;
if(a.length() == b.length()){ //长度相等说明是同性
G[abs(stoi(a))].push_back(abs(stoi(b))); //用abs来减少判断代码
G[abs(stoi(b))].push_back(abs(stoi(a)));
}
}
scanf("%d",&k);
while(k--){
int a,b;
cin>>a>>b;
vector<pair<int,int> > ans;
int cnt = 0;
//从两者的同性人中找
for(int i=0;i<G[abs(a)].size();i++){
int c = G[abs(a)][i];
if(c == abs(b)) continue;
for(int j=0;j<G[abs(b)].size();j++){
int d = G[abs(b)][j];
if(d == abs(a)) continue;
if(re[c][d]){
cnt++;
ans.push_back(make_pair(c,d));
}
}
}
sort(ans.begin(), ans.end(), cmp);
printf("%d\n",cnt);
for(int i=0;i<ans.size();i++){
printf("%04d %04d\n", ans[i].first, ans[i].second);
}
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步