题目描述:
One day, a useless calculator was being built by Kuros. Let's assume that number X is showed on the screen of calculator. At first, X = 1. This calculator only supports two types of operation.
1. multiply X with a number.
2. divide X with a number which was multiplied before.
After each operation, please output the number X modulo M.
输入:
The first line is an integer T(1≤T≤10), indicating the number of test cases.
For each test case, the first line are two integers Q and M. Q is the number of operations and M is described above. (1≤Q≤,1≤M≤
)
The next Q lines, each line starts with an integer x indicating the type of operation.
if x is 1, an integer y is given, indicating the number to multiply. (0<y≤)
if x is 2, an integer n is given. The calculator will divide the number which is multiplied in the nth operation. (the nth operation must be a type 1 operation.)
It's guaranteed that in type 2 operation, there won't be two same n.
输出:
For each test case, the first line, please output "Case #x:" and x is the id of the test cases starting from 1.
Then Q lines follow, each line please output an answer showed by the calculator.
样例输入:
1 10 1000000000 1 2 2 1 1 2 1 10 2 3 2 4 1 6 1 7 1 12 2 7
样例输出:
Case #1: 2 1 2 20 10 1 6 42 504 84
线段树真的是太神奇了,开始完全想不到这竟然能用线段树来做,神奇。
这个题的题意就是给出Q个操作,把Q次操作当做Q个节点,每次输入两个数a和b,当a=1,就乘以b;当a=2,就把b节点的值更新为1。题目里说的是当a=2的时候,是除以第b次操作的那个数,这里我们不用除以那个数,就把第b个节点更新为1就行了,因为当a等于1的时候是一系列的连乘操作,把那个地方更新成1,乘了也和没乘一样。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
const int maxn=100005;
long long ans[maxn<<2];//这里必须用longlong 用int会WA,我的理解是当a=1时,乘的那个
int m,t,q,a,b;//数是10的9次方,会超出int的范围
void pushup(int rt)
{
ans[rt]=ans[rt<<1]*ans[rt<<1|1]%m;
}
void build(int l,int r,int rt)
{
if(l==r)
{
ans[rt]=1;
return ;
}
int m=(l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushup(rt);
}
void updata(int L,int C,int l,int r,int rt)
{
if(l==r&&l==L)//更新,一定要找到要更新的L节点,然后更新它
{
ans[rt]=C;
return ;
}
int m=(l+r)>>1;
if(L<=m)updata(L,C,l,m,rt<<1);
else updata(L,C,m+1,r,rt<<1|1);
pushup(rt);
}
int main()
{
int res=1;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&q,&m);
build(1,q,1);
printf("Case #%d:\n",res++);
for(int i=1;i<=q;i++)
{
scanf("%d%d",&a,&b);
if(a==1)
updata(i,b,1,q,1);
else if(a==2)
updata(b,1,1,q,1);
printf("%d\n",ans[1]);
}
}
return 0;
}