USACO training chapter1 入门/section1.5

本文解析了USACO训练中两道经典题目:算术序列与母乳问题。算术序列题通过枚举公差和起点实现深度优先搜索;母乳问题则直接枚举所有可能状态,避免重复计算。代码采用C++实现,展示了如何使用DFS和预处理技巧解决算法问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

USACO training chapter1 入门/section1.5

简单的搜索入门,只有两题,都可以用深搜来做,第二题可广搜,但是代码很烦,用dfs简单点。

Arithmetic Progressions

先枚举公差,然后枚举起点。
貌似可以证明公差只需要+4的枚举。
注意枚举范围,否则会很慢。

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int max_n = 250.* 250 * 2;
int n, m;
int bisq[max_n + 50];
bool dfs(int s, int d, int l) {
    if (l > n) return true;
    if (!bisq[s]) return false;
    return dfs(s + d, d, l + 1);
}
 
int main() {
    //cin >> n >> m;
    scanf("%d%d", &n, &m);
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= m; j++) {
            bisq[i * i + j * j] = 1;  //提前打好表。       
        }
    }
     
    int f = 0;
    for (int d = 1; d <= 2 * m * m; d++) {
        for (int s = 0; s + (n-1) * d <= 2 * m * m; s++) {
            if (dfs(s, d, 1)) {
                f = 1;
                //cout << s << " " << d << endl;
                printf("%d %d", s, d); //输出多的话,cout会超时。
            }
        }
    }
    if (f == 0) printf("NONE\n");
    return 0;
}

Mother’s Milk

很直接的题,直接写出所有可能的情况就好了,注意陷入不要死循环,对于已经处理过的情况标记一下。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> vt;
int L1, L2, L3;
int vis[30][30][30];
int used[30];

void dfs(int a, int b, int c) {
    if (vis[a][b][c]) return ;
    if (a == 0 && !used[c]) {
        vt.push_back(c);
        used[c] = 1;
    }
    vis[a][b][c] = 1;
    
    if (a <= L2 - b) dfs(0, b + a, c);
    else dfs(a - L2 + b, L2, c);
    if (a <= L3 - c) dfs(0, b, c + a);    
    else dfs(a - L3 + c, b, L3);
    
    if (b <= L1 - a) dfs(a + b, 0, c);
    else dfs(L1, b - L1 + a, c);
    if (b <= L3 - c) dfs(a, 0, b + c);
    else dfs(L1, b - L3 + c, L3);
    
    if (c <= L1 - a) dfs(a + c, b, 0);
    else dfs(L1, b, c - L1 + a);
    if (c <= L2 - b) dfs(a, b + c, 0);
    else dfs(a, L2, c - L2 + b);
    
}

int main() {
    cin >> L1 >> L2 >> L3;
    dfs(0, 0, L3);
    sort(vt.begin(), vt.end());
    for (int i = 0; i < (int)vt.size(); i++)
        cout << vt[i] << " ";
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值