从0节点到其他节点的最长路径(相邻两点长度为1)

#include<bits/stdc++.h>
using namespace std ;
int N ; //节点个数

int main(){
	
	cin>>N; 
	bool a[N][N];
	memset(a,0,sizeof(a));
	for(int i=0;i<N-1;i++){
		int x,y;
		cin>>x>>y;
		a[x][y] = true ;
		a[y][x] = true ;
	}
	//初始化结束
	bool isVisited[N] ;
	memset(isVisited,0,sizeof(isVisited));

	int max_length = 0 ;
	int max_res =INT_MIN;
	bool * p = (bool *)isVisited ;
	bool * q = (bool *)a;
	function<void(int)> fun ;
	fun = [&](int node){ //lambdah函数实现深度递归
		*(p+node) = true ;
		int i=0;
		for(i=0;i<N ;i++){
			if( *(q+node*N+i)==true  &&  *(p+i)==false){
				max_length += 1 ;
				fun(i);
				max_length -=1;
			}
		}
		if(i==N && max_length>max_res)  max_res = max_length; 		
	};
	fun(0);
	cout<<max_res<<"-----"<<endl;
	return 0;
}

输入:
9
0 1
0 3
4 8
6 7
5 6
1 4
1 2
3 5

输出:

4

PS:在主函数中,使用lambda函数实现递归,因为数组N的大小是运行时确定的,因此无法传递给主函数之外的函数作为实参,并且对于lambda函数的理解有多了一层

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值