揹包問題
//簡陋版**
#include
using
namespace std;
const
int maxn =30;
int n,v,maxvalue =0;
//物品件數n,揹包容量v,最大價值maxvalue
int w[maxn]
,v[maxn]
;//index為當前處理的物品的編號
//sumw和sumv分別為當前的總重量和總價值
void
dfs(
int index,
int sumw,
int sumv)
return;}
//岔道口
dfs(index+
1,sumw,sumv)
;//不選第index件物品
dfs(index+
1,sumw+w[index]
,sumv+v[index]);
//選第index件物品
}int
main()
for(
int i=
0;i)dfs(0
,0,0
);cout
}//岔路口是:對於每個物品都有選擇或者不選擇兩種可能
//死胡同是一旦當前所有物品的總和超過v,就需要返回最近的岔路口
#include
using
namespace std;
const
int maxn =30;
int n, v, maxvalue =0;
//物品件數n,揹包容量v,最大價值maxvalue
int w[maxn]
, v[maxn]
;//index為當前處理的物品的編號
//sumw和sumv分別為當前的總重量和總價值
void
dfs(
int index,
int sumw,
int sumv)
//岔道口
dfs(index +
1, sumw, sumv)
;//不選第index件物品
//只有加入第index件物品後未超過容量v,才能繼續
if(sumw + w[index]
<= v)
dfs(index +
1, sumw + w[index]
, sumv + v[index]);
//選擇第i件物品}}
intmain()
for(
int i =
0; i < n; i++
)dfs(0
,0,0
);cout << maxvalue << endl;
return0;
}//岔路口是:對於每個物品都有選擇或者不選擇兩種可能
//死胡同是一旦當前所有物品的總和超過v,就需要返回最近的岔路口
#include
#include
using
namespace std;
const
int maxn =60;
int n;
int d[maxn]
;int p[maxn]
;int ans =
1e10
;//需要準備的金幣個數
//index:當前遇見的怪物
//sum:當前的武力值
//money:當前需要的金幣數
void
dfs(
int index,
int sum,
int money)
//如果當前武力值大於當前怪物武力值,可以選擇賄賂或者不賄賂
if(sum >= d[index]
)else
//當前的武力值小於怪物武力值,只能賄賂
}int
main()
for(
int i =
0; i < n; i++
)dfs(0
,0,0
);cout
}
模板1
#include
#include
using
namespace std;
int dx[4]
=;int dy[4]
=;const
int maxn =
100;
char maze[maxn]
[maxn]
;//迷宮矩陣
bool vis[maxn]
[maxn]=;
//記錄位置(x,y)是否已入過
int n, m;
//矩陣大小為n*m
struct node
s, t, node;
//開始節點,結束節點,臨時節點
bool
judge
(int x,
int y)
else
if(vis[x]
[y]==
true
|| maze[x]
[y]==
'*')
return
true;}
intbfs
(int x,
int y)
for(
int i =
0; i <
4; i++)}
}return-1
;//無法到達終點時,返回-1
}int
main()
} cin >> s.x >> s.y >> t.x >> t.y;
//起點和終點的座標
cout <<
bfs(s.x, s.y)
<< endl;
return0;
}
DFS,BFS演算法總結
乙個典型的實現 深度優先遍歷演算法 1 鄰接矩陣的深度優先遍歷演算法 void adjmwgraph depth int v,int visited 故用鄰接矩陣表示圖時,搜尋乙個頂點的所有鄰接點需花費o n 時間,則從n個頂點出發搜尋的時間應為o n 2 即dfs演算法的時間複雜度是 n2 2 鄰...
演算法筆記 DFS BFS
深度優先搜尋 dfs void dfs if 越界或者是不合法狀態 return if 特殊狀態 剪枝 return for 擴充套件方式 dfs 幾道題目 推薦做一下 例項1 全排列加素數 已知 n 個整數b1,b2,bn 以及乙個整數 k k n 從 n 個整數中任選 k 個整數相加,可分別得到...
Miller Rabin素數測試演算法模板對比
昨天在usaco做了一道判斷素數的題,就想著學習一下miller rabin素數測試演算法,在網上找到兩種模版,第一種十分簡潔,執行速度也很快,但是會判錯極少的幾個非素數 第二種比較麻煩,執行速度很慢,所以我便想找到第一種模版不能判斷的非素數特判一下,結果用了一天,電腦只找到10 8以下的,10 9...