题意:求树上最长路。
解题思路:dfs + dp
解题代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // File Name: 120F.cpp 2 // Author: darkdream 3 // Created Time: 2015年03月24日 星期二 14时51分16秒 4 5 #include<vector> 6 #include<list> 7 #include<map> 8 #include<set> 9 #include<deque> 10 #include<stack> 11 #include<bitset> 12 #include<algorithm> 13 #include<functional> 14 #include<numeric> 15 #include<utility> 16 #include<sstream> 17 #include<iostream> 18 #include<iomanip> 19 #include<cstdio> 20 #include<cmath> 21 #include<cstdlib> 22 #include<cstring> 23 #include<ctime> 24 #define LL long long 25 #define maxn 105 26 using namespace std; 27 int dp[maxn]; 28 int n; 29 int mx; 30 vector<int> mp[maxn]; 31 void dfs(int k ,int la) 32 { 33 for(int i = 0 ;i < mp[k].size() ;i ++) 34 { 35 if( mp[k][i] == la) 36 continue; 37 dfs(mp[k][i],k); 38 mx = max(mx,dp[k] + dp[mp[k][i]]+1); 39 dp[k] = max(dp[k],dp[mp[k][i]] + 1); 40 } 41 } 42 int main(){ 43 freopen("input.txt","r",stdin); 44 freopen("output.txt","w",stdout); 45 int t; 46 scanf("%d",&t); 47 int sum = 0; 48 while(t--) 49 { 50 scanf("%d",&n); 51 for(int i= 1 ;i <= 100 ;i ++) 52 mp[i].clear(); 53 memset(dp,0,sizeof(dp)); 54 for(int i = 1;i < n;i ++) 55 { 56 int ta , tb ; 57 scanf("%d %d",&ta,&tb); 58 mp[ta].push_back(tb); 59 mp[tb].push_back(ta); 60 } 61 mx = 0 ; 62 dfs(1,0); 63 //printf("***%d\n",mx); 64 sum += mx; 65 } 66 printf("%d\n",sum); 67 68 return 0; 69 }
没有梦想,何谈远方