cf1277 D. Let's Play the Words?

链接

点击跳转

题解

这题妙啊

首先注意到一个事实, 0...0 0...0 1...1 1...1 这种其实对我们的接龙不会有什么影响,不管把这种串接在哪里,都不会影响我们的局面。除了“只有这两种串”的情况需要特判输出 1 -1 之外,其余时候我们完全可以撇开这种串,考虑只有 0...1 0...1 1...0 1...0 的问题。

那么显然当 0...1 0...1 1...0 1...0 这两种串的数量差不超过 1 1 时,才能组成接龙。那么我们就把数量较多的那种串不停的反转,直到满足条件。

代码

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 1000010
#define maxe 1000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(_,__) for(_=1;_<=(__);_++)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
    ll c, f(1);
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
    for(;isdigit(c);c=getchar())x=x*10+c-0x30;
    return f*x;
}
ll n;
unordered_set<string> s01, s10;
vector<string> v(maxn);
vector<ll> p01, p10;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll i, T;
    string s;
    cin>>T;
    while(T--)
    {
        v.clear();
        s10.clear();
        s01.clear();
        p01.clear();
        p10.clear();
        cin>>n;
        rep(i,n)
        {
            cin>>v[i];
            auto a=v[i][0]-0x30, b=v[i].back()-0x30;
            if(a==0 and b==1)s01.em(v[i]);
            if(a==1 and b==0)s10.em(v[i]);
        }
        ll n01=s01.size(), n10=s10.size(), n00=0, n11=0;
        rep(i,n)
        {
            auto s=v[i], rev=s;
            auto a=s[0]-0x30, b=s.back()-0x30;
            if(a==b){n00+=!a;n11+=a;continue;}
            reverse(rev.begin(),rev.end());
            if(a==0 and s10.find(rev)==s10.end())p01.emb(i);
            if(a==1 and s01.find(rev)==s01.end())p10.emb(i);
        }
        if(n01==0 and n10==0)
        {
            if(n00==0 or n11==0)
            {
                cout<<"0\n\n";
            }
            else cout<<"-1\n";
            continue;
        }
        vector<ll> ans;
        while(abs(n01-n10)>1)
        {
            if(n01>n10)
            {
                if(p01.empty())break;
                n01--, n10++;
                ans.emb(p01.back());
                p01.pop_back();
            }
            else
            {
                if(p10.empty())break;
                n10--, n01++;
                ans.emb(p10.back());
                p10.pop_back();
            }
        }
        if(abs(n01-n10)<=1)
        {
            cout<<ans.size()<<'\n';
            for(auto x:ans)cout<<x<<' ';
            cout<<'\n';
        }
        else
        {
            cout<<"-1\n";
        }
    }
    return 0;
}
发布了863 篇原创文章 · 获赞 72 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/FSAHFGSADHSAKNDAS/article/details/103915635