求助
查看原帖
求助
727556
wangziwenhk楼主2024/4/9 16:10
#include <bits/stdc++.h>

using namespace std;
const int N = 2e5+10;
class graph{
public:
    map<int,vector<int>>G;
    stack<int>s;
    int dfn[N],low[N],cnt=0;
    bool vis[N];
    int sc=0;
    unordered_map<int,int>scc_size,scc;
    void tarjan(int x){
        dfn[x]=low[x]=++cnt;
        vis[x]=true;
        s.push(x);
        for(auto i:G[x]){
            if(!dfn[i]){
                tarjan(i);
                low[x]=min(low[x],low[i]);
            }
            else if(vis[i]){
                low[x]=min(low[x],low[i]);
            }
        }
        if(low[x]==dfn[x]){
            ++sc;
            while(s.top()!=x){
                scc[s.top()]=sc;
                scc_size[sc]++;
                vis[s.top()]=false;
                s.pop();
            }
            scc[s.top()]=sc;
            scc_size[sc]++;
            vis[s.top()]=false;
            s.pop();
        }
    }
}G;
unordered_map<int,int>inNode;
unordered_map<int,bool>vis;
char cnt = 'a'-1;
void dfs(int x,int pre){
    vis[x]=true;
    if(G.scc[pre]==G.scc[x])cout<<cnt;
    else cout<<++cnt;
    for(auto i:G.G[x]){
        if(!vis[i])
            dfs(i,x);
    }
}
int main() {
    int n,k,pre,x;
    cin>>n>>k;
    for(int _=1;_<=2;_++){
        pre=-1;
        for(int i=1;i<=n;i++){
            cin>>x;
            if(pre!=-1){
                G.G[pre].push_back(x);
            }
            pre=x;
        }
    }
    G.tarjan(1);
    if(G.scc.size()<k){
        cout<<"NO";
    }
    else{
        cout<<"YES"<<endl;
        for(int i=1;i<=n;i++){
            for(int j=0;j<G.G[i].size();j++){
                if(G.scc[i]!=G.scc[G.G[i][j]]){
                    inNode[G.scc[G.G[i][j]]]++;
                }
            }
        }
        for(int i=1;i<=G.sc;i++){
            if(inNode[i]==0){
                for(auto j:G.scc){
                    if(j.second==i){
                        dfs(j.first,-1);
                        return 0;
                    }
                }

            }
        }
    }
    return 0;
}

2024/4/9 16:10
加载中...