Leetcode 990. 方程式の充足可能性 方程式 Floyd/ Union 検索 + シミュレーション

元のリンク: Leetcode 990. 方程式の充足可能性

ここに画像の説明を挿入
ここに画像の説明を挿入
フロイド

class Solution {
    
    
public:
    bool equationsPossible(vector<string>& equations) {
    
    
        vector<vector<int>> g(26,vector<int>(26));
        for(int i=0;i<26;i++) g[i][i]=1;
        for(auto x:equations)
        {
    
    
            int a=x[0]-'a';
            int b=x[3]-'a';
            char ch=x[1];
            if(ch=='=')
            {
    
    
                g[a][b]=1;  g[b][a]=1;
            }
            if(ch=='!' && g[a][b]) return false;
        }
        for(int k=0;k<26;k++)
        {
    
    
            for(int i=0;i<26;i++)
            {
    
    
                for(int j=0;j<26;j++)
                {
    
    
                    if(g[i][k] && g[k][j]) g[i][j]=1;
                }
            }
        }
        for(auto x:equations)
        {
    
    
            int a=x[0]-'a';
            int b=x[3]-'a';
            char ch=x[1];
            if(ch=='!' && g[a][b]) return false;
            if(ch=='=' && !g[a][b]) return false;
        }
        return true;
    }
};

そしてルックアップ

class Solution {
    
    
public:
    map<int,int> fa;
    int findfather(int x)
    {
    
    
        int a=x;
        while(x!=fa[x]) x=fa[x];
        while(a!=fa[a])
        {
    
    
            int z=a;
            a=fa[a];
            fa[z]=x;
        }
        return x;
    }
    void Union(int x,int y)
    {
    
    
        int fx=findfather(x);
        int fy=findfather(y);
        if(fx!=fy)
        {
    
    
            if(fx<fy) fa[fy]=fx;
            else fa[fx]=fy;
        }
    }
    bool equationsPossible(vector<string>& equations) {
    
    
        for(int i=0;i<26;i++) fa[i]=i;
        for(auto x:equations)
        {
    
    
            int a=x[0]-'a';
            int b=x[3]-'a';
            char ch=x[1];
            if(ch=='=') Union(a,b);
        }
        for(auto x:equations)
        {
    
     
            char ch=x[1];
            if(ch=='!')
            {
    
    
                int a=x[0]-'a';
                int b=x[3]-'a';
                int fx=findfather(a);
                int fy=findfather(b);
                if(fx==fy) return false;
            } 
        }
        return true;
    }
};

おすすめ

転載: blog.csdn.net/qq_45791939/article/details/128029548