1907G - Lights - CodeForces Solution


constructive algorithms dfs and similar graphs greedy implementation

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
using ll=long long;
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
template<class T> bool chmax(T &a, T b){if (a < b){a = b;return true;} else return false;}
template<class T> bool chmin(T &a, T b){if (a > b){a = b;return true;} else return false;}

void solve(){
    int N;
    string S;
    cin>>N>>S;
    vector<int>A(N),ind(N);
    vector<bool>flag(N);
    for(int i=0;i<N;i++){
        cin>>A[i];
        A[i]--;
        ind[A[i]]++;
        if(S[i]=='1')flag[i]=true;
    }
    queue<int>q;
    for(int i=0;i<N;i++){
        if(ind[i]==0)q.push(i);
    }
    vector<int>ans;
    while(q.size()){
        int x=q.front();
        q.pop();
        if(ind[A[x]]>0){
            ind[A[x]]--;
            if(flag[x]){
                flag[x]=false;
                flag[A[x]]=!flag[A[x]];
                ans.push_back(x+1);
            }
            if(ind[A[x]]==0){
                q.push(A[x]);
            }
        }
    }
    for(int i=0;i<N;i++){
        if(ind[i]>0&&flag[i]){
            int at=i;
            bool light=true;
            int x=1,y=1;
            while(1){
                at=A[at];
                if(at==i)break;
                if(flag[at]){
                    light=!light;
                }
                if(light)x++;
                y++;
                ind[at]--;
            }
            if(light){
                cout<<-1<<"\n";
                return;
            }
            light=true;
            while(1){
                if(light==(x<=y-x)){
                    ans.push_back(at+1);
                }
                at=A[at];
                if(at==i)break;
                if(flag[at]){
                    light=!light;
                }
            }
        }
    }
    cout<<(int)ans.size()<<"\n";
    for(auto a:ans)cout<<a<<" ";
    cout<<"\n";
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
}


Comments

Submit
0 Comments
More Questions

1092B - Teams Forming
1166C - A Tale of Two Lands
544B - Sea and Islands
152B - Steps
1174D - Ehab and the Expected XOR Problem
1511A - Review Site
1316A - Grade Allocation
838A - Binary Blocks
1515D - Phoenix and Socks
1624D - Palindromes Coloring
1552F - Telepanting
1692G - 2Sort
1191A - Tokitsukaze and Enhancement
903A - Hungry Student Problem
52B - Right Triangles
1712A - Wonderful Permutation
1712D - Empty Graph
1712B - Woeful Permutation
1712C - Sort Zero
1028B - Unnatural Conditions
735B - Urbanization
746C - Tram
1278B - A and B
1353D - Constructing the Array
1269C - Long Beautiful Integer
1076A - Minimizing the String
913C - Party Lemonade
1313A - Fast Food Restaurant
681A - A Good Contest
1585F - Non-equal Neighbours