做法
贪心做法。
回顾简单题做法。根据摆放顺序,对于一个确定情况,如果 是 (当然 不贡献),贡献 ,如果是 ,贡献 。( 从 开始编号)
然后最小化代价,首先判断情况是否合法。
如果存在 中任意一个为 ,那么直接非法,否则如果是 直接设为 。
其次除 这个位置外, 一定不劣于 。而且 这个位置为 ,对答案贡献为 没有任何影响。
所以考虑已经确定的情况的方案乘起来是 。如果它已经是 的倍数,无论如何最后答案都不可能不是 的倍数。
如果不是,二分一下最多几个位置 不会使答案为 的倍数。然后以此确定至少选择多少 的位置,从小到大考虑选择奇数,如果选择了这个奇数会导致答案不合法,跳过选择下一个即可。
偶数一定会提供 ,而还不如直接将他选择为 。所以如果奇数的个数满足不了选 的个数,那么则一定非法。
代码
Accepted code
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
const int N=2e5+10;
int T,n,c;
string s;
int lcm(int x,int y)
{
int g=__gcd(x,y);
return g*(x/g)*(y/g);
}
int mypow(int a,int k,int p)
{
a%=p;
if(k==0)return 1;
int res=a;
k--;
while(k)
{
if(k&1)res=(res*a)%p;
a=(a*a)%p;
k>>=1;
}
return res;
}
void solve()
{
cin>>n>>c>>s;
if(s[0]=='0' || s[s.size()-1]=='0')
{
cout<<"-1\n";
return ;
}
int op=1,cnt=0;
if(s[0]=='?')s[0]='1';
if(s[s.size()-1]=='?')s[s.size()-1]='1';
if(s[1]=='?')s[1]='0';
if(c<=2)
{
cout<<"-1\n";
return ;
}
int ans=1;
for(int i=1;i<s.size();i++)
{
if(s[i]=='0')
{
ans=(ans*i)%mod;
op=(op*i)%c;
}
else if(s[i]=='1')
{
ans=(ans*2)%mod;
op=(op*2)%c;
}
else cnt++;
}
if(op==0)cout<<"-1\n";//答案只可能是当前答案的倍数
else
{
int l=0,r=cnt,res=0;
while(l<=r)
{
int mid=(l+r)/2;
if((mypow(2,mid,c)*op)%c)
{
res=max(res,mid);
l=mid+1;
}
else r=mid-1;
}
cnt-=res;
ans=(ans*mypow(2,res,mod))%mod;
for(int i=2;i<s.size()&&cnt;i++)
{
if(s[i]=='?' && i%2)
{
int oop=(op*i)%c;
if(oop)
{
ans=(ans*i)%mod;
cnt--;
op=(op*i)%c;
}
}
}
if(cnt)cout<<"-1\n";
else cout<<ans<<"\n";
}
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>T;
while(T--)solve();
return 0;
}