Codeforces 522 A. Reposts 树形DP

本文介绍了一种解决树形结构中寻找最长路径的问题。通过使用map将字符串节点转换为整数,构建树形结构,并采用深度优先搜索(DFS)算法来确定树中最长的边。代码实现包括字符串转换、树的构建及DFS遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击打开链接

题目大意:给你一棵树,求出这颗树上最长的边。

思路:用map把字符串转换成数字,然后建树,从根节点深搜,一层一层搜下去。

建树的方法:利用vector 


ACcode:

/*
2017年10月13日19点40分
AC

*/
#include <iostream>
#include <map>
#include <set>
#include <string>
#include<string.h>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn=220;
int dp[maxn];
int ans=0;
vector<int> G[maxn];
map<string,int> mp;
string t="polycarp";

void trans(string &s){
    int len=s.length();
    for(int i=0;i<len;i++){
        s[i]=tolower(s[i]);
    }
}

void dfs(int u,int root){
    dp[u]=1;
    int len=G[u].size();
    for(int i=0;i<len;i++){
        int v=G[u][i];
        if(v==root) continue;
        dfs(v,u);
        dp[u]=max(dp[u],dp[v]+1);
        ans=max(dp[u],ans);
    }
}


int main(){
    int n;
    scanf("%d",&n);
    string a,b,c;
    int num=0;
    memset(dp,0,sizeof(dp));
    mp.clear();
    for(int i=0;i<maxn;i++){
        G[i].clear();
    }
    for(int i=0;i<n;i++){
        cin>>a>>b>>c;
        trans(a);
        trans(c);
        if(!mp[a])  mp[a]=++num;
        if(!mp[c])  mp[c]=++num;
        G[mp[a]].push_back(mp[c]);
        G[mp[c]].push_back(mp[a]);
    }
    dfs(mp[t],-1);
    printf("%d\n",ans);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值