CodeForces-1131D

D. Gourmet choice

Topic links: https://codeforces.com/problemset/problem/1131/D

 

Topic effect: NULL

Problem-solving ideas: such as over an equals sign between two dishes, then their number should be the same, so we need to reduce operating point,

It should be used disjoint-set, and then is to determine the order between the dish, because there is a relationship between them, we can consider the construction side between two points, this time on the need to use

Topological sorting can

 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e4+10;
int pre[maxn],in[maxn],out[maxn],vis[maxn],ans[maxn];
vector<int>g[maxn];
int find(int i)
{
  if(i==pre[i]) return pre[i];
  else return find(pre[i]);
}
void unions(int x,int y)
{
    int xx=find(x);
    int yy=find(y);
    if(xx!=yy) pre[xx]=yy;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n+m;i++)
    {
        pre[i]=i;
    }
    char s[1100][1100];
    for(int i=1;i<=n;i++)
    {
        scanf("%s",s[i]+1);
        for(int j=1;j<=m;j++)
        {
            if(s[i][j]=='=') unions(i,j+n);
            /*else if(s[i][j]=='>') g[find(j+n)].push_back(find(i)),in[find(i)]++;
            else g[find(i)].push_back(find(j+n)),in[find(j+n)]++;*/
        }
    }
     for(int i=1; i<=n; i++){
        for(int j=1; j<=m; j++)
        if(s[i][j] == '>'){
           g[find(j+n)].push_back(find(i)); in[find(i)]++;
        }
        else if(s[i][j] == '<') g[find(i)].push_back(find(j+n)),in[find(j+n)]++;
    }
    stack<int>q;
    for(int i=1;i<=n+m;i++)
    {
        if(in[find(i)]==0)
        {
        //    cout<<find(i)<<endl;
            q.push(find(i));
            vis[find(i)]=1;
            ans[find(i)]=1;
        }
    }
    while(!q.empty())
    {
        int u=q.top();
        q.pop();
        for(int i=0;i<g[u].size();i++)
        {
            int v=g[u][i];
            in[find(v)]--;
            if(in[find(v)]==0&&!vis[find(v)])
            {
                 vis[find(v)]=1;
                 ans[find(v)]=ans[find(u)]+1;
                 q.push(find(v));
            }
        }
    }
    for(int i=1;i<=n+m;i++)
    {
        if(!vis[find(i)])
        {
            cout<<"NO\n";
            return 0;
        }
    }
    cout<<"YES"<<endl;
    for(int i=1;i<=n;i++)
    {
        if(i!=1) cout<<" ";
        cout<<ans[find(i)]; 
    }
    cout<<endl;
    for(int i=1;i<=m;i++)
    {
        if(i!=1) cout<<" ";
        cout<<ans[find(i+n)]; 
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/tombraider-shadow/p/11622494.html