首页 > 代码库 > SDUT 3085-路线冲突问题(迭代深搜)

SDUT 3085-路线冲突问题(迭代深搜)

题目链接:点击打开链接

求两条路径的交点的个数(保证路径唯一)深搜一发。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cctype>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define maxn 100010
#define _ll __int64
#define ll long long
#define INF 0x3f3f3f3f
#define Mod 1000000007
#define pp pair<int,int>
#define ull unsigned long long
using namespace std;
int n, s1, s2, e1, e2, path[maxn], x[maxn], y[maxn], ok;
vector <int> eg[maxn];
bool vis[maxn];
void dfs(int u, int e)
{
	if (ok) {
		return ;
	}

	if (u == e) {
		ok = 1;
		return ;
	}

	for (int i = 0; i < eg[u].size(); i++) {
		int v = eg[u][i];

		if (!vis[v]) {
			path[v] = u;
			vis[v] = 1;
			dfs(v, e);

			if (ok) {
				return ;
			}

			path[v] = -1;
			vis[v] = 0;
		}
	}
}
void solve()
{
	memset(path, -1, sizeof(path));
	memset(vis, 0, sizeof(vis));
	vis[s1] = 1;
	ok = 0;
	dfs(s1, e1);
	int numx = 0, t = e1;

	while (path[t] != -1) {
		x[numx++] = t;
		t = path[t];
	}

	x[numx++] = s1;
	memset(path, -1, sizeof(path));
	memset(vis, 0, sizeof(vis));
	vis[s2] = 1;
	ok = 0;
	dfs(s2, e2);
	int numy = 0;
	t = e2;

	while (path[t] != -1) {
		y[numy++] = t;
		t = path[t];
	}

	y[numy++] = s2;
	sort(y, y + numy);
	int ans = 0;

	for (int i = 0; i < numx; i++)
		if (binary_search(y, y + numy, x[i])) {
			ans++;
		}

	if (ans) {
		printf("%d\n", ans);
	} else {
		puts("success");
	}
}
int main()
{
	int u, v;

	while (~scanf("%d", &n)) {
		for (int i = 1; i <= n; i++) {
			eg[i].clear();
		}

		n--;

		while (n--) {
			scanf("%d %d", &u, &v);
			eg[u].push_back(v);
			eg[v].push_back(u);
		}

		scanf("%d %d %d %d", &s1, &e1, &s2, &e2);
		solve();
	}

	return 0;
}


SDUT 3085-路线冲突问题(迭代深搜)