HDU - 5475 An easy problem (思维+数学+线段树)

版权声明:本文为博主原创文章,转载请附上注明就行_(:з」∠)_。 https://blog.csdn.net/vocaloid01/article/details/82703740

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.

Input

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≤105,1≤M≤109)
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≤109)
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.

Output

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.

Sample Input

1
10 1000000000
1 2
2 1
1 2
1 10
2 3
2 4
1 6
1 7
1 12
2 7

Sample Output

Case #1:
2
1
2
20
10
1
6
42
504
84

题意:

初始X=1,有两种操作:

1.X乘上一个整数y。

2.X除以一个之前乘过的数。

要求每次操作之后,输出X%M的值

思路:

这道题咋一看好像是个简单的模拟题,但是仔细一想会发现除法直接除肯定不行(因为有取余操作啊)。那么最正确的做法就是将每次乘的数存起来,输出结果时直接把所有存的数乘起来就行了。而因为除的都是之前乘过的数,所以只需要把存的对应位置的乘数变成1就行了,这样就把除法转换成了乘法,进而排除了取余操作的影响。

当然这样做的时间复杂度是O(n^2),但我们可以通过线段树维护每次操作的数,这样时间复杂度就降到了O(nlogn)。

另外这题数据可能比较水,O(n^2)其实直接就能过。

代码:

#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = 100005;

long long Tree[4*MAXN],MOD;

void Up(int temp){
	Tree[temp] = (Tree[temp<<1]*Tree[temp<<1|1])%MOD;
}

void Build(int temp,int left,int right){
	Tree[temp] = 1;
	if(left == right)return ;
	int m = left + (right-left)/2;
	Build(temp<<1,left,m);
	Build(temp<<1|1,m+1,right);
}

void Updata(int temp,int left,int right,int tempt,int value){
	if(left == right){
		Tree[temp] = value;
		return ;
	}
	int m = left + (right-left)/2;
	if(tempt<=m)Updata(temp<<1,left,m,tempt,value);
	else Updata(temp<<1|1,m+1,right,tempt,value);
	Up(temp);
}

int main(){
	
	int T,N;
	scanf("%d",&T);
	for(int _=1 ; _<=T ; ++_){
		printf("Case #%d:\n",_);
		scanf("%d %d",&N,&MOD);
		Build(1,1,N);
		for(int i=1 ; i<=N ; ++i){
			int a,b;
			scanf("%d %d",&a,&b);
			if(a == 1){
				Updata(1,1,N,i,b);
				printf("%lld\n",Tree[1]);
			}
			else {
				Updata(1,1,N,b,1);
				printf("%lld\n",Tree[1]);
			}
		}
	}
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/vocaloid01/article/details/82703740