原题链接
题目大意
给定一个n个整数组成的序列。你每次可以用序列中两个相邻的数和替代这两个数(即将两个数合并成他们的和)。请经过若干次操作后,使得序列中含有p的倍数的数字个数最多。
题解
从1开始向n遍历,求和,求和结果sum对p取模,然后判断结果是否出现过,如果成立,ans++,对sum清空。
证明:设上次出现的位置为last,那么last-now这个区间的值相加的值为p的倍数。
使用到了贪心的思想:即在更早的区间使结果+1,不会比最优结果差。
标程
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int ans;
int n,p;
int A[maxn];
map<long,bool> MAP;
void sovle()
{
long res=0;
MAP.clear();
for (int i = 0; i <n; i++)
{
res+=A[i];
res%=p;
if(MAP[res] || res==0)
{
ans++;
res=0;
MAP.clear();
}
else
MAP[res]=1;
}
//cout<<endl;
}
int main()
{
//freopen("1004in.in","r",stdin);
int t;
scanf("%d",&t);
while (t--)
{
ans=0;
scanf("%d%d",&n,&p);
for (int i = 0; i < n; i++)
{
scanf("%d",&A[i]);
}
sovle();
printf("%d\n",ans);
}
return 0;
}
本文介绍了一种算法,通过遍历整数序列并使用贪心策略,求得序列中能被p整除的元素的最大数量。该算法利用了求和与取模运算,结合映射记录历史状态,实现高效求解。
962

被折叠的 条评论
为什么被折叠?



