社区讨论

简单代码求条(悬1关)

P10124 [USACO18OPEN] Family Tree B参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@m2lxlddu
此快照首次捕获于
2024/10/23 21:49
去年
此快照最后确认于
2025/11/04 16:23
4 个月前
查看原帖
CPP
//
// Created by 55062 on 2024/10/23.
//
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
ll n,tot=2,root,dep[110],anc[110][30],lg2[30],x=1,y=2;
string a,b,xx,yy;
bool flag=true,aaa=false,bbb=false;
map<string,ll> id;
vector<ll> v[110],fa[110];
void dfs(ll x,ll father){
    anc[x][0]=father;
    dep[x]=dep[father]+1;
    for(int i=1;(1<<i)<=dep[x];i++) anc[x][i]=anc[anc[x][i-1]][i-1];
    for(int i=0;i<v[x].size();i++) dfs(v[x][i],x);
}ll lca(ll x,ll y){
    if(dep[x]<dep[y]) swap(x,y);
    while(dep[x]>dep[y]){x=anc[x][lg2[dep[x]-dep[y]]];}
    if(x==y) return x;
    for(int i=lg2[dep[x]];i>=0;i--)
        if(anc[x][i]!=anc[y][i]){
            x=anc[x][i];
            y=anc[y][i];
        }
    return anc[x][0];
}void dfs2(ll x){
    for(int i=0;i<v[x].size();i++){
        if(v[x][i]==1) aaa=true;
        if(v[x][i]==2) bbb=true;
        dfs2(v[x][i]);
    }
}
int main() {
    cin>>n>>a>>b;
    id[a]=1,id[b]=2;
    for(int i=1;i<=n;i++){
        cin>>xx>>yy;
        if(id.count(xx)==0) tot++,id[xx]=tot;
        if(id.count(yy)==0) tot++,id[yy]=tot;
        v[id[xx]].push_back(id[yy]);
        fa[id[yy]].push_back(id[xx]);
    }for(int i=2;i<=tot;i++)  lg2[i]=lg2[i>>1]+1;
    for(int i=1;i<=tot;i++)
        if(fa[i].size()==0){
            if(root!=0) flag=false;
            root=i;
        }
    if(flag==false)
        for(int i=1;i<=tot;i++)
            if(fa[i].size()==0){
                if(aaa!=bbb){
                    cout<<"NOT RELATED";
                    exit(0);
                }dfs2(i);
            }
    dfs(root,0);
    ll nx=lca(1,2),n=dep[1]-dep[nx],m=dep[2]-dep[nx];
    if(n==1&&m==1) cout<<"SIBLINGS";
    else if(n==0){
        cout<<a<<" is the ";
        while(m>=3){
            cout<<"great-";
            m--;
        }if(m==2) cout<<"grand-";
        cout<<"mother of "<<b;
    }else if(m==0){
        cout<<b<<" is the ";
        while(n>=3){
            cout<<"great-";
            n--;
        }
        if(n==2) cout<<"grand-";
        cout<<"mother of "<<a;
    }else if(n==1){
        cout<<a<<" is the ";
        while(m>=3){
            cout<<"great-";
            m--;
        }cout<<"aunt of "<<b;
    }else if(m==1){
        cout<<b<<" is the ";
        while(n>=3){
            cout<<"great-";
            n--;
        }cout<<"aunt of "<<a;
    }else cout<<"COUSINS";
    return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...