團體程式設計天梯賽-練習集-L2-016. 願天下有情人都是失散多年的兄妹(dfs)

來源:互聯網
上載者:User

記錄一個菜逼的成長。。

題目連結

一看題目,我以為可以用LCA演算法寫,寫了半天,後來發現不是樹(woc…)
再看題目,不超過5代,那麼直接暴搜咯、、

查詢時,標記一個人的不超過5代的祖先,再從另一個人向上搜尋在5代內是否有標記過的祖先。

#include <bits/stdc++.h>using namespace std;#define ALL(v) (v).begin(),(v).end()#define cl(a,b) memset(a,b,sizeof(a))#define clr clear()#define pb push_back#define mp make_pair#define fi first#define se secondtypedef pair<int,int> PII;const int maxn = 100000 + 10;int sex[maxn],vis[maxn],used[maxn];vector<int>tree[maxn];void dfs1(int x,int cnt){    vis[x] = 1;    if(cnt == 4){        return ;    }    for( int i = 0; i < tree[x].size(); i++ ){        if(!vis[tree[x][i]]){            dfs1(tree[x][i],cnt+1);        }    }}bool dfs2(int x,int cnt){    if(cnt == 5){        return false;    }    if(vis[x]){        return true;    }    used[x] = 1;    bool ret = false;    for( int i = 0; i < tree[x].size(); i++ ){        if(!used[tree[x][i]]){            ret = (ret || dfs2(tree[x][i],cnt+1));        }    }    return ret;}int main(){    int n;    while(~scanf("%d",&n)){        int x,y,z;        char s[10];        cl(sex,-1);        for( int i = 0; i < n; i++ ){            scanf("%d%s%d%d",&x,s,&y,&z);            sex[x] = (s[0] == 'M' ? 1 : 0);            if(y != -1){                tree[x].pb(y);                sex[y] = 1;            }            if(z != -1){                tree[x].pb(z);                sex[z] = 0;            }        }        int q;scanf("%d",&q);        while(q--){            scanf("%d%d",&x,&y);            if(sex[x] == sex[y])puts("Never Mind");            else {                cl(vis,0);cl(used,0);                dfs1(x,0);                bool ans = dfs2(y,0);                puts(ans?"No":"Yes");            }        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.