L2-031 深入虎穴——最短路模型

L2-031 深入虎穴——最短路模型_第1张图片

DFS

#include

using namespace std;
int n,res,id;//res最大深度,id最大深度的编号
const int N = 1e5 + 10;
vector v[N];
bool st[N];

int dfs(int u,int sum)
{
	if (sum > res)
		res = sum,id = u;
	
	for (auto x : v[u])
		dfs(x, sum + 1);

}

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i]) 
			start = i;
	dfs(start,1);
	cout << id;
}

BFS

#include
using namespace std;
int n, res, id;
const int N = 1e5 + 10;
vector v[N];
bool st[N];

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i])
			start = i;

	queue q;
	q.push(start);
	while (q.size())
	{
		int t = q.front();
		q.pop();
		if (q.size() == 0)  res = t;
		for (auto x : v[t])
			q.push(x);
	}
	cout << res;

}

如果还想求一下路径的话

#include
using namespace std;
int n, res, id;
const int N = 1e5 + 10;
vector v[N];
bool st[N];
int pre[N];

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i])
			start = i;

	queue q;
	q.push(start);
	pre[start] = -1;
	while (q.size())
	{
		int t = q.front();
		q.pop();
		if (q.size() == 0)  res = t;
		for (auto x : v[t])
		{
			q.push(x);
			pre[x] = t;
		}
	}
	cout << res << endl;
	vector path;
	while (pre[res] != -1)
	{
		path.push_back(res);
		res = pre[res];
	}path.push_back(start);
	reverse(path.begin(), path.end());
	for (auto x : path) cout << x << " ";
}

L2-031 深入虎穴——最短路模型_第2张图片

 很明显bfs来做,这里用dist既表示了距离也有st数组的功能

#include
using namespace std;
const int N = 2e5 + 10;
int dist[N];
int n, k;
int bfs(int x)
{
	queue q;
	q.push(x);
	memset(dist, -1, sizeof dist);
	dist[x] = 0;


	while (q.size())
	{
		int t = q.front();
		q.pop();

		if (t - 1 >= 0 && t - 1 < N&& dist[t-1]==-1)
	        q.push(t - 1), dist[t - 1] = dist[t] + 1;
	
		if (t + 1 >= 0 && t + 1 < N && dist[t+1]==-1)
		    q.push(t + 1), dist[t + 1] = dist[t] + 1;
		
		if (2 * t >= 0 && 2 * t < N && dist[2*t]==-1)
		    q.push(2 * t), dist[2 * t] = dist[t] + 1;

		if (dist[k] != -1) return dist[k];
	}
	return -1;
}

int main()
{

	cin >> n >> k;
	cout << bfs(n);
}

你可能感兴趣的:(深度优先,算法,c++)