日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【dfs】P1036 选数

發布時間:2025/3/21 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【dfs】P1036 选数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接:https://www.luogu.com.cn/problem/P1036

考點:素數、dfs、組合


題意:給n個整數,從中選取k個求和,統計“和為素數”的次數。

做法一(直接dfs):
dfs,3個參數分別記錄了數組下標起點、當前已選數的和、當前已選數量。

#include <bits/stdc++.h> using namespace std;int A[25]; int cnt = 0; int n,k; bool isprime(int x) {if (x == 0 || x == 1) return true;for (int i = 2; i <= sqrt(x); i++) {if (x % i == 0) return false;}return true; }void dfs(int sta, int sum, int total) {if (total == k) {//cout << sum << endl; // debugif (isprime(sum)) cnt++;return;} for (int i = sta; i < n; i++) {dfs(i + 1, sum + A[i], total + 1); // 從起點的下一個數開始取數,已選數+1} }int main() {cin >> n >> k;for (int i = 0; i < n; i++) cin >> A[i];dfs(0, 0, 0);cout << cnt;return 0; }

一開始沒想到可以用dfs,只是想著能遍歷出所有組合情況就好了。

解法二(遍歷組合):
不就是求每種組合的和嗎,遍歷就完事兒了。

遍歷組合的算法:https://blog.csdn.net/Kwansy/article/details/103538652

#include <bits/stdc++.h> using namespace std; const int Max = 20; int A[Max]; int cnt = 0;bool isprime(int x) {if (x == 0 || x == 1) return true;for (int i = 2; i <= sqrt(x); i++) {if (x % i == 0) return false;}return true; }void dfs(int sta, int n, int k, int cur) {static int R[Max];if (cur == k) {int sum = 0;for (int i = 0; i < k; i++) {//cout << R[i] << " ";sum += R[i];}if (isprime(sum)) cnt++;return;}for (int i = sta; i < n; i++) { // 遍歷起點R[cur] = A[i];dfs(i+1, n, k, cur+1);} }int main() {int n,k; cin >> n >> k;for (int i = 0; i < n; i++) cin >> A[i];dfs(0, n, k, 0); // 從第0個開始取,總長n,取k個,當前已取0cout << cnt;return 0; }

總結

以上是生活随笔為你收集整理的【dfs】P1036 选数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。