您的位置:首页 > 其它

UVA 11916 Emoogle Grid(同余模)

2013-11-27 17:19 387 查看
题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3067

题意:用K种颜色给一个N*M的格子涂色。其中有B个格子是不能涂色的。涂色时满足同一列上下紧邻的两个格子的颜色不同。所有的涂色方案模100000007后为R。现在给出M、K、B、R,求一个最小的N,满足题意。

思路:设给出的B个不能涂的格子的最大行坐标为maxX。首先,我们能计算出前maxX行的方案数ans,若ans=R则maxX就是答案。接着,我们能计算出前maxX+1行的方案数ans1,若ans1=R则答案为 maxX+1。否则,设下面还需要t行,那么有ans1*((K-1)^M)^t%100000007=R,将ans1的逆元乘到右侧得到新的R'=R*reverse(ans1),令p=(K-1)^M。那么就成了求最小的t满足p^t%100000007=R'。

int Pow(int x,int y)
{
int ans=1;
while(y)
{
if(y&1) ans=(i64)ans*x%mod;
x=(i64)x*x%mod;
y>>=1;
}
return ans;
}

int Pow(int x,int y,int mod)
{
int ans=1;
while(y)
{
if(y&1) ans=(i64)ans*x%mod;
x=(i64)x*x%mod;
y>>=1;
}
return ans;
}

int exGcd(int a,int b,int &x,int &y)
{
if(!b)
{
x=1; y=0;
return a;
}
int temp=exGcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
return temp;
}

int reverse(int a,int b)
{
int x,y;
exGcd(a,b,x,y);
x=x%b;
if(x<0) x+=b;
return x;
}

int logMod(int a,int b,int n)
{
int m=sqrt(n+0.5);
int v=reverse(Pow(a,m,n),n);
map<int,int> mp;
int x=1,i;
mp[1]=0;
for(i=1;i<m;i++)
{
x=(i64)x*a%n;
if(!mp.count(x)) mp[x]=i;
}
FOR0(i,m)
{
if(mp.count(b)) return i*m+mp[b];
b=(i64)b*v%n;
}
return -1;
}

int m,R,K,B,p;

int cal(int x)
{
if(x<=0) return 1;
if(x==1) return K;
int ans=(i64)K*Pow(K-1,x-1,mod)%mod;
return ans;
}

int cal(vector<int> V,int maxX)
{
int pre=0,ans=1,i;
FOR0(i,SZ(V))
{
ans=(i64)ans*cal(V[i]-pre-1)%mod;
pre=V[i];
}
ans=(i64)ans*cal(maxX-pre)%mod;
return ans;
}

void cal(vector<int> V
,int n,int maxX)
{
int temp,i,x=m-n;
int ans=Pow(cal(maxX),x);
for(i=1;i<=n;i++)
{
temp=cal(V[i],maxX);
ans=(i64)ans*temp%mod;
temp=SZ(V[i])-1;
if(V[i][temp]<maxX) x++;
}
if(ans==R) PR(maxX);
else
{
ans=(i64)ans*Pow(K-1,x)%mod*Pow(K,m-x)%mod;
if(ans==R) PR(maxX+1);
else
{
temp=(i64)reverse(ans,mod)*R%mod;
PR(maxX+1+logMod(p,temp,mod));
}
}
}

int main()
{
int num=0;
rush()
{
RD(m,K); RD(B,R);
vector<int> V
;
map<int,int> mp;
int i,x,y,t=0,maxX=0;
FOR1(i,B)
{
RD(x,y);
if(!mp.count(y)) mp[y]=++t;
V[mp[y]].pb(x);
maxX=max(maxX,x);
}
FOR1(i,t) sort(V[i].begin(),V[i].end());
p=Pow(K-1,m,mod);
printf("Case %d: ",++num);
int ans;
if(maxX==0)
{
ans=Pow(K,m);
if(ans==R) puts("1");
else
{
ans=(i64)reverse(ans,mod)*R%mod;
PR(1+logMod(p,ans,mod));
}
}
else cal(V,t,maxX);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: