题意:求a到b中间经过两个节点的路径,与a相连的节点属性(性别)与a一样,与b相连的节点属性(性别)与b一样,求出数量,并按第一节点非递减顺序输出每一条路径的节点,第一个节点一样按第二个节点从小到大输出。
在输入所有边后,将每个点的相连的边按节点大小从小到大排序,然后进行深度优先搜索,先找到a的同性节点(不能是b),再找b的同性节点(不能是a),保存路径,统计数量。
这一题刚写完就有几个点通不过,看了一下别人的讲解可能是输入正负0的问题,于是修改原来用大小判断性别的方法,用一个数组将性别记下来,一开始的边输入用字符串,然后提交还是有错误,看了一下别人的讲解,发现是我输出没有按四位输出。(以为很简单,有点心浮气躁了)
(用时:1:47:25.73)
#include <bits/stdc++.h>
using namespace std;
const int INF = 10000000;
const int LEN = 10000;
vector<int> friends[LEN];
vector<vector<int> > pathQue;
int genders[LEN]= {0};
int pathNum = 0;
void DFS(int x,int y,int genderX,int genderY,int num,int currentIndex,vector<int> pathVec,int vis[])
{
if(num==3) {
pathNum++;
// printf("------\n");
vector<int> path = pathVec;
pathQue.push_back(path);
return;
}
int gender = genderX;
if(num>=1) {
gender = genderY;
}
vis[currentIndex] = 1;
for(int i=0; i<friends[currentIndex].size(); i++) {
if(num<2&&vis[friends[currentIndex][i]]==0&& genders[friends[currentIndex][i]] == gender &&friends[currentIndex][i]!=y) {
// printf("%d %d %d\n",currentIndex,friends[currentIndex][i],num);
pathVec[num]=friends[currentIndex][i];
DFS(x,y,genderX,genderY,num+1,friends[currentIndex][i],pathVec,vis);
} else if(num==2&&friends[currentIndex][i]==y) {
DFS(x,y,genderX,genderY,num+1,friends[currentIndex][i],pathVec,vis);
}
}
vis[currentIndex] = 0;
}
bool cmp(int a,int b)
{
return abs(a) < abs(b);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int x,y,t;
vector<int> bAg;
int visit[LEN] = {0};
string a,b;
for(int i=0; i<m; i++) {
cin>>a>>b;
x = abs(atoi(a.c_str()));
if(a.length() >4) {
genders[x] = -1;
} else {
genders[x] = 1;
}
if(!visit[x]) {
visit[x] = 1;
bAg.push_back(x);
}
y = abs(atoi(b.c_str()));
if(b.length() >4) {
genders[y] = -1;
} else {
genders[y] = 1;
}
if(!visit[y]) {
visit[y] = 1;
bAg.push_back(y);
}
friends[x].push_back(y);
friends[y].push_back(x);
}
for(int i=0; i<bAg.size(); i++) {
sort(friends[bAg[i]].begin(),friends[bAg[i]].end());
}
int k;
scanf("%d",&k);
int genderX,genderY;
for(int i=0; i<k; i++) {
scanf("%d%d",&x,&y);
pathNum = 0;
int vis[LEN] = {0};
pathQue.clear();
vector<int> pathVec(2);
x = abs(x);
y = abs(y);
DFS(x,abs(y),genders[x],genders[y],0,x,pathVec,vis);
printf("%d\n",pathNum);
for(int j=0; j<pathNum; j++) {
printf("%04d %04d\n",pathQue[j][0],pathQue[j][1]);
}
}
return 0;
}