当前位置:网站首页>Gym - 102219j kitchen plates (violent or topological sequence)

Gym - 102219j kitchen plates (violent or topological sequence)

2022-07-07 09:47:00 moyangxian

The question : A little

. :
Practice one : A topological sort . Five plates are equivalent to a digraph with five points ,A<B amount to A One side points to B. Then do it again after drawing based on BFS Topology sorting of .
Time complexity O(5+5)

#include<bits/stdc++.h>

using namespace std;
const int N=10;
int head[N],tot;
int s[N];
vector<int>ans;
struct Edge{
    
    int to,next;
}e[N];

void init(){
    
    memset(head,-1,sizeof(head));
    memset(s,0,sizeof(s));
    tot=0;
}

void addedge(int u,int v){
    
    e[tot].to=v;
    e[tot].next=head[u];
    head[u]=tot++;
}

bool topsort(){
    
    queue<int>q;
    for(int i=0;i<5;i++)
        if(!s[i]){
    
            q.push(i);
            ans.push_back(i);
        }
    while(!q.empty()){
    
        int u=q.front();
        q.pop();
        for(int i=head[u];~i;i=e[i].next){
    
            int v=e[i].to;
            if(--s[v]==0){
    
                q.push(v);
                ans.push_back(v);
            }
        }
    }
    return ans.size()==5;
}

int main(){
    
    init();
    for(int i=0;i<5;i++){
    
        char u,v,op;
        cin>>u>>op>>v;
        if(op=='>') swap(u,v);
        addedge(u-'A',v-'A');
        s[v-'A']++;
    }
    if(!topsort()) cout<<"impossible"<<endl;
    else{
    
        for(int i=0;i<ans.size();i++)
            cout<<(char)(ans[i]+'A');
        cout<<endl;
    }
    return 0;
}

Practice two :
violence .next_permutation() Work out "ABCDE" The whole arrangement , Then check whether the arrangement meets the conditions of the topic .
Time complexity O(5!)

#include<bits/stdc++.h>

using namespace std;
const int N=10;
char a[]={
    'A','B','C','D','E'};
char s[5][3];

bool check(){
    
    for(int i=0;i<5;i++){
    
        int p1,p2;
        for(int j=0;j<5;j++){
    
            if(a[j]==s[i][0]) p1=j;
            if(a[j]==s[i][2]) p2=j;
        }
        if(p1>p2) return false;
    }
    return true;
}

int main(){
    
    for(int i=0;i<5;i++){
    
        cin>>s[i];
        if(s[i][1]=='>') swap(s[i][0],s[i][2]);
    }
    do{
    
        if(check()) break;
    }while(next_permutation(a,a+5));
    if(check()) for(int i=0;i<5;i++) cout<<a[i];
    else cout<<"impossible"<<endl;
    return 0;
}

原网站

版权声明
本文为[moyangxian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070709202130.html