Reposts(dfs)

One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp’s joke to their news feed. Some of them reposted the reposts and so on.

These events are given as a sequence of strings “name1 reposted name2”, where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string “name1 reposted name2” user “name1” didn’t have the joke in his feed yet, and “name2” already had it in his feed by the moment of repost. Polycarp was registered as “Polycarp” and initially the joke was only in his feed.

Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp’s joke.

Input
The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as “name1 reposted name2”. All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.

We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

Output
Print a single integer — the maximum length of a repost chain.

Examples
Input
5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya
Output
6
题目分析:
这道题只要一开始全部字母处理成小写或大写,数字和‘/’不用管的。还有一点要注意的是他们转发的顺序可能不是连续的,可能隔了好多个人又转发了一连串,只要注意这一点就行了。深搜很轻松。
代码:

#include<iostream>
#include<string>
using namespace std;
int shu[201],n;
string a[201],b,c[201];
int dfs(string ok,int len,int st)
{
    int l=len;
    for(int i=st+1;i<=n;i++)
    {
        if(c[i]==ok)
        {
            l=max(l,dfs(a[i],len+1,i));//取最大值
        }
    }
    return l;
}
int main()
{
    int ans=1;
    cin>>n;
    string t="polycarp";
    int l=1;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        for(int j=0;j<a[i].size();j++)
            if(a[i][j]>='A'&&a[i][j]<='Z') a[i][j]+=32;
        cin>>b;
        cin>>c[i];
        for(int j=0;j<c[i].size();j++)
            if(c[i][j]>='A'&&c[i][j]<='Z') c[i][j]+=32;
        if(c[i]==t) {
            shu[l++]=i;
        }
    }
    int len;
    string ok;
    for(int i=1;i<=l-1;i++)
    {
        len=2;
        ok=a[shu[i]];
        ans=max(dfs(ok,len,shu[i]),ans);//取最大值
    }
    cout<<ans;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章