PAT1139 First Contact
原题链接:PAT1139
解析:这题真的很有陈越老师的风范。。。五个数据点没有一个是随机生成数据的,每个测试点都对应一个细节。
- 由于是用'-'来表示女生,而int型读入数据如果是-0000,则表示为0,这样就丢失了性别,故需要用字符串读入
- 由于输出是要求四位数id,若id为0012,则%d会输出12,故需要%04d输出
- 如果是同性恋,那么要保证a找的朋友不能是b,b找的朋友不能是a
代码实例:修修改改,可读性较差,见谅
#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int maxn = 310;
int gender[maxn];
vector<int> G[maxn];
map<int,int> ID,rID;
typedef pair<int,int> pi;
vector<pi> ans;
int s[maxn][maxn];
int cnt = 0;
int get_id(int x){
if(ID.count(x)) return ID[x];
ID[x] = cnt++;
rID[ID[x]] = x;
return ID[x];
}
void Love(int a,int b){
int id_a = get_id(a);
int id_b = get_id(b);
for(int i = 0;i < G[id_a].size();i++){
int u = G[id_a][i];
if(gender[u] == gender[id_a] && u != id_b)
for(int j = 0;j < G[id_b].size();j++){
int v = G[id_b][j];
if(gender[id_b] == gender[v] && v != id_a)
if(s[u][v]) ans.push_back(make_pair(u,v));
}
}
}
bool cmp2(pi a,pi b){
int ax = rID[a.first]*gender[a.first];
int ay = rID[a.second]*gender[a.second];
int bx = rID[b.first]*gender[b.first];
int by = rID[b.second]*gender[b.second];
if(ax == bx) return ay < by;
return ax < bx;
}
int read(){
char str[10];
scanf("%s",str);
int sn = 0;
int sng = 1;
if(str[0] == '-'){
sng = -1;
for(int i = 1;i <= 4;i++) sn = sn*10+str[i]-'0';
}
else
for(int i = 0;i < 4;i++) sn = sn*10+str[i]-'0';
sn *= sng;
if(str[0] == '-') gender[get_id(sn)] = -1;
else gender[get_id(sn)] = 1;
return sn;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
for(int i = 0;i < m;i++){
a = read();
b = read();
int id_a = get_id(a);
int id_b = get_id(b);
G[id_a].push_back(id_b);
G[id_b].push_back(id_a);
s[id_a][id_b] = 1;
s[id_b][id_a] = 1;
}
int k;
scanf("%d",&k);
for(int i = 0;i < k;i++){
scanf("%d%d",&a,&b);
ans.clear();
Love(a,b);
sort(ans.begin(),ans.end(),cmp2);
cout << ans.size() << endl;
for(int j = 0;j < ans.size();j++){
int one = ans[j].first;
int another = ans[j].second;
printf("%04d %04d\n",rID[one]*gender[one],rID[another]*gender[another]);
}
}
return 0;
}