Cod sursa(job #1758878)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 18 septembrie 2016 00:18:19
Problema Episoade Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.97 kb
#include <cstdio>
#include <cctype>
#include <vector>
#include <algorithm>

#define MAXP 1000
#define MAXN 100

char s[MAXP+1];
int t[MAXN+1], poz, ans;
int l[MAXN+1], r[MAXN+1];

bool cmp(const int a, const int b){
    return l[a]<l[b];
}

int find(int x){
    if(t[x]==x) return x;
    else return t[x]=find(t[x]);
}

inline void unite(int x, int y){
    t[x]=y;
    if(l[x]<l[y]) l[y]=l[x];
    if(r[x]>r[y]) r[y]=r[x];
}

int expr();

int factor(){
    if(ans==0) return 0;
    if(s[poz]=='('){
        poz++;
        int x=expr();
        poz++;
        return x;
    }else{
        int x=0;
        while(isdigit(s[poz])){
            x=10*x+s[poz]-'0';
            poz++;
        }
        return find(x);
    }
}

int termen(){
    if(ans==0) return 0;
    int x=factor(), y;
    while(s[poz]=='>'){
        poz++;
        y=factor();
        if(r[find(x)]+1!=l[find(y)]) ans=0;
        else unite(find(x), find(y));
        x=y;
    }
    return find(x);
}

int expr(){
    if(ans==0) return 0;
    std::vector <int> v;
    v.push_back(termen());
    while(s[poz]=='#'){
        poz++;
        v.push_back(termen());
    }
    std::sort(v.begin(), v.end(), cmp);
    for(int i=1; i<(int)v.size(); i++){
        if(r[find(v[i-1])]+1!=l[find(v[i])]) ans=0;
        else unite(find(v[i-1]), find(v[i]));
    }
    return find(v[0]);
}

int main(){
    int n, x, q;
    char ch;
    FILE *fin, *fout;
    fin=fopen("episoade.in", "r");
    fout=fopen("episoade.out", "w");
    ch=fgetc(fin);
    n=0;
    while(ch!='\n'){
        s[++n]=ch;
        ch=fgetc(fin);
    }
    s[++n]=ch;
    fscanf(fin, "%d%d", &q, &n);
    for(int i=1; i<=q; i++){
        for(int j=1; j<=n; j++){
            fscanf(fin, "%d", &x);
            l[x]=r[x]=j;
            t[x]=x;
        }
        poz=1;
        ans=1;
        x=expr();
        fprintf(fout, "%d\n", ans);
    }
    fclose(fin);
    fclose(fout);
    return 0;
}