佳佳有一个n*m的带权矩阵,她想从(1,1)出发走到(n,m)且只能往右往下移动,她能得到的娱乐值为所经过的位置的权的总和。
有一天,她被下了恶毒的诅咒,这个诅咒的作用是将她的娱乐值变为对p取模后的值,这让佳佳十分的不开心,因为她无法找到一条能使她得到最大娱乐值的路径了!
她发现这个问题实在是太困难了,既然这样,那就只在3*n的矩阵内进行游戏吧!
现在的问题是,在一个3*n的带权矩阵中,从(1,1)走到(3,n),只能往右往下移动,问在模p意义下的移动过程中的权总和最大是多少。
样例解释:
移动的方案为“下下右”。
Input
单组测试数据 第一行两个数n(1<=n<=100000),p(1<=p<=1000000000)。 接下来3行,每行n个数,第i行第j列表示a[i][j]表示该点的权(0<=a[i][j]<p)。
Output
一个整数表示答案。
Input示例
2 3 2 2 2 2 0 1
Output示例
2#include <algorithm> #include <cstring> #include <iostream> #include <stdio.h> #include <set> using namespace std; const int MAXN = 1e5 + 10; typedef long long int ll; ll a[3][MAXN]; ll sum[3][MAXN]; int n; ll p; int main() { sum[0][0] = 0; sum[1][0] = 0; sum[2][0] = 0; cin >> n >> p; for (int i = 0; i < 3; i++) { for (int j = 1; j <= n; j++) { scanf("%d", &a[i][j]); sum[i][j] = (sum[i][j - 1] + a[i][j]) % p; } } set<ll> buf; ll result = 0; for (int i = 1; i <= n; i++) { ll temp = (sum[0][i] - sum[1][i - 1] + p) % p; buf.insert(temp); temp = (sum[1][i] + sum[2][n] - sum[2][i - 1] + p) % p; set<ll>::iterator it = buf.lower_bound(p - temp); if (it != buf.begin()) { result = max(result, (temp + *(--it)) % p); } } cout << result << endl; return 0; }