Codeforces 567C Geometric Progression (离散 + DP)

@(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的个数 n xk的个数 m <script type="math/tex" id="MathJax-Element-10">m</script>,这样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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值