Codeforces 567C Geometric Progression (离散 + DP)

来源:互联网 发布:网络空间安全好就业吗 编辑:程序博客网 时间:2024/05/21 22:39

@(K ACMer) by 题解工厂


题意:

给你一个序列,求序列中长度为3的公比为k的子序列的个数.


分析:

典型的情况数量问题,一看就应该想到用DP去解决,不难想到一个数x为结尾的长度为i的子序列等于,以它前面的数x/k结尾的长度为i-1的子序列数.

定义:dp[i][j] 以j结尾的长度为i的子序列的个数
有转移方程

dp[i][j]=dp[i1][j/k]

注意这里的数j/k必须位于数列中j之前的位置,所以这里实现的时候运用了一个边转移边添加元素的方法,非常经典,且由于树的大小为109这里用了map数组来离散化查找,详细见代码

除了DP由于这个子序列的长度仅为3,我们还可以用构造的方法:

枚举数列中的每个元素作为子序列中间的元素x,然后分别到左边去查找x/k的个数nxk的个数m,这样m*n就是以x为中间元素的子序列个数.这里把所有数的存到map中查的时候到map中去查多少个,但是同样要用到边构成边查的技巧,要不然你不能去查这个数之前的x/k出现多少次.


DP的Code:

#include <bits/stdc++.h>using namespace std;typedef long long LL;map<int, LL> dp[4];int n, k, v[200000+100];int main(void){    cin >> n >> k;    for (int i = 0; i < n; i++)        scanf("%d", &v[i]);    LL ans = 0;    for (int j = 0; j < n; j++) {        int x = v[j];        if (x % k == 0) {            ans += dp[2][x / k];            dp[2][x] += dp[1][x / k];        }        dp[1][x] += 1;    }    cout << ans << endl;    return 0;}

构造的Code:

#include <iostream>#include <cstdio>#include <string>#include <algorithm>#include <set>#include <map>#include <vector>#include <queue>#include <iterator>#include <cmath>#include <cstring>#include <cstdlib>using namespace std;typedef long long LL;const int INF = 0x3fffffff, M = 200009;LL a[M], b[M], c[M];int main(void){    int n, k;    while (~scanf("%d%d", &n, &k)) {        map<long long,long long> m;        memset(a, 0 ,sizeof(a));        memset(b, 0, sizeof(b));        memset(c, 0, sizeof(c));        for (int i = 0; i < n; i++) {            scanf("%I64d", &a[i]);            if (a[i] % k == 0) {                b[i] = m[a[i] / k];            }            m[a[i]]++;            c[i] = m[a[i] * k];        }        LL ans = 0;        for (int i = 0; i < n; i++) {            LL l, ll;            l = b[i];            ll = m[a[i] * k] - c[i];            //if (k == 1) ll--;            ans += l * ll;        }        printf("%I64d\n", ans);    }    return 0;}
0 0