By Jalan
知识工具需求
数据结构和算法
- DFS
题干
通过两个中间人找对象
题解
第一次
思路
- 输入要注意-0的存在,同一个编号不会有2个性别.所以用一个hash表来存是不是女生
- DFS,注意剪枝,这里我放了一个写在一个DFS的情况,实际上可以把两人是同性别和不同性别分开写,这样可以让逻辑更清晰.
- 统一两个DFS的时候借鉴了一个老哥的代码,但是我实在找不到那个老哥的网页了(中途接了对象电话顺便吃了个饭关机了),对不起,砰砰砰…
编写用时
60分钟
代码
CPP
#include <algorithm>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
typedef struct node
{
int first, second;
} node;
const int maxN = 10010;
int n, m;
vector<vector<int>> g(maxN);
vector<int> isGirl(maxN);
int start, ed;
int first, second;
vector<node> ans;
vector<int> test(6);
bool cmp(node a, node b)
{
return a.first != b.first ? a.first < b.first : a.second < b.second;
}
void DFS2(int index, int depth)
{
if (depth == 2)
{
if (index == ed ||index==start|| isGirl[index] != isGirl[start])//index == ed ||index==start||防止同性时找自己
{
return;
}
first=index;
}
if (depth == 3)
{
if (index == ed ||index==start||isGirl[index] != isGirl[ed])//index == ed ||index==start||防止同性时找自己
{
return;
}
second=index;
}
if (depth == 4)
{
if (index != ed)
{
return;
}
ans.push_back(node{first, second});
return;
}
for (int i = 0; i < g[index].size(); i++)
{
int v = g[index][i];
if (v != index)//有向..
{
DFS2(v, depth + 1);
}
}
}
int main(int argc, char const *argv[])
{
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++)
{
char u[10], v[10];
scanf("%s %s", u, v);
string as(u), bs(v);
int a = abs(stoi(as));
int b = abs(stoi(bs));
if (as[0] == '-')
{
isGirl[a] = 1;
}
if (bs[0] == '-')
{
isGirl[b] = 1;
}
g[a].push_back(b);
g[b].push_back(a);
}
int k;
scanf("%d", &k);
for (int i = 0; i < k; i++)
{
scanf("%d %d", &start, &ed);
start = abs(start);
ed = abs(ed);
ans.clear();
DFS2(start, 1);
printf("%d\n", ans.size());
sort(ans.begin(), ans.end(), cmp);
for (int j = 0; j < ans.size(); j++)
{
printf("%04d %04d\n", ans[j].first, ans[j].second);
}
}
return 0;
}
运行用时
结尾
看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀
@.@
也欢迎关注我的CSDN账号呀=]
**开心code每一天**