CF577B Modulo Sum(dp,抽屉原理 | bitset优化 | 二进制优化)

 洛谷链接:

Modulo Sum - 洛谷

思路:

明显是一个背包问题,要求子序列和整除m,即sum%m = 0,所以边取模边求和即可。但是朴素做法的时间复杂度是O(nm),会TLE。有三种优化思路:

1.抽屉原理优化,n如果大于m直接输出YES。理由是:假如计算ai的前缀和,前n个数就有n个前缀和。假如n > m,n个sum值取模之后必定至少有两个值相等,假如sum(j) - sum(i) = 0,那么从 i 到 j 的连续序列的和必定被m整除。

2.bitset优化,实际上还是暴力思路,只是换成位运算导致更快了而已。

3.二进制优化,把mod m相同的数字进行计数,然后分成1,2,4,8...2n,rest 这n+1份,二进制优化可参见洛谷”樱花“这道题。

#include 
using namespace std;
const int maxm = 1e3+5;
int n, m, a[maxm];
bool f[maxm][maxm];
int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    if(n>m) {cout<<"YES"; return 0;} //抽屉原理特判
    for(int i=1; i<=n; i++)
        cin >> a[i], a[i] %= m;

    for(int i=1; i<=n; i++){
        f[i][a[i]] = 1;
        for(int j=0; j
#include
using namespace std;
const int maxm=1e3+5;
int n, m;
bitset<1000> f[2];
int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for(int i=1; i<=n; i++){
        int t; cin >> t; t %= m;
        int cur = i&1, pre = cur^1;
        f[cur] = f[pre] | (f[pre]<>(m-t));
        f[cur][t] = 1;
    }
    for(int i=0; i<1000; i+=m){
        if(f[n&1][i]) {cout<<"YES"; return 0;}
    }
    cout<<"NO";
}
#include 
using namespace std;
const int maxm = 1e3+5;
int n, m, a[maxm], t;
int b[20000], cnt;
int f[2][maxm];

void init(){
    for(int i=0; i=p){
            b[++cnt] = (i*p)%m;
            a[i] -= p;
            p *= 2;
        }
        if(a[i]) b[++cnt] = (i*a[i])%m;
    }
}
int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for(int i=1; i<=n; i++){
        cin>>t; t %= m;
        a[t]++;
    }
    init();
    for(int i=1; i<=cnt; i++){
        int c=i&1;
        for(int j=0; j

 

你可能感兴趣的:(算法)