Stay Hungry,Stay Foolish!

D - Change Usernames -- ATCODER

D - Change Usernames

https://atcoder.jp/contests/abc285/tasks/abc285_d

 

思路

DFS深度遍历图。

需要注意的是, 整个大图中可能有很多小的连通子图,

每个子图需要确定起始访问节点,起始节点为没有入度的节点。

同时还需要注意的是, 有些特殊子图,没有上述起始节点, 自身就是一个环图。

Code

https://atcoder.jp/contests/abc285/submissions/38164255

int n;
map<string, map<string, bool>> edges;
map<string, bool> vis;
map<string, int> indegree;
 
int main()
{
    cin >> n;
 
    for(int i=0; i<n; i++){
        string s, t;
        cin >> s >> t;
        edges[s][t] = true;
        
        vis[s] = false;
        vis[t] = false;
        
        indegree[s] += 0;
        indegree[t] += 1;
    }
 
    vector<string> snodes;
    for(auto it: indegree){
        string str = it.first;
        int count = it.second;
 
        if (count == 0){
            snodes.push_back(str);
        }
    }
 
    int sindex = 0;
    while(true){
        string fs;
 
        if (sindex >= snodes.size()){
            break;
        }
        
        fs = snodes[sindex];
//        cout << "fs=" << fs << endl;
        sindex++;
 
        stack<string> st;
        st.push(fs);
        while(!st.empty()){
            string top = st.top();
            st.pop();
            
            if (vis[top] == true){
                cout << "No" << endl;
                return 0;
            } 
            
            vis[top] = true;
            
            for(auto itr: edges[top]){
                st.push(itr.first);
            }
        }
    }
    
    // if there is some nodes
    // which is not visited
    // it means cycle exists
    for(auto it: vis){
        bool visited = it.second;
        if (visited == false){
            cout << "No" << endl;
            return 0;
        }
    }
    
    cout << "Yes" << endl;
 
    return 0;
}
 

 

posted @ 2023-01-20 12:59  lightsong  阅读(47)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel