[NOIP2001]数的划分
DFS
#include<bits/stdc++.h>
using namespace std;
int n,k,res;
struct Num {
int now,cnt;
};
void DFS(Num num,int pos) {//DFS遍历
if(num.cnt==1&&num.now>=pos) {//最后一次递归的时候
++res;
return ;
}
for(int i=(pos?pos:1); i<=num.now; ++i) {//按照单调不减序列排
DFS({num.now-i,num.cnt-1},i);//递归为将now-i这个数划分为cnt-i份,每份不为空
}
}
int main() {
scanf("%d%d",&n,&k);
DFS({n,k},0);
printf("%d\n",res);
}
动态规划
#include<bits/stdc++.h>
using namespace std;
#define M 500
int n,k;
int dp[M][M];
void init() {
for(int i=1; i<=n; ++i) {
dp[i][1]=1;//dp初始化
}
}
int main() {
scanf("%d%d",&n,&k);
init();
for(int i=2; i<=n; ++i) {
for(int j=2; j<=k; ++j) {
if(i>j)dp[i][j]=dp[i-1][j-1]+dp[i-j][j];//先对j个分块预置为1
else dp[i][j]=dp[i-1][j-1];//依次拿一个数出来
}
}
printf("%d\n",dp[n][k]);
}
NOIP2014寻找道路
BFS
先找出所有可以到达end的点,对他们进行标记。再对每个节点node进行遍历,看它的子节点,如果有一个子节点未被标记,那么被遍历的该节点node失去资格
#include<bits/stdc++.h>
using namespace std;
#define M 100000
const int INF = 0x3f3f3f3f;
int n, m, s, t;
int dis[M], vis[M];
vector<int> vi[M], revVi[M];
int Bfs(int beg) {
fill(dis + 1, dis + 1 + n, INF);//
dis[beg] = 0;
queue<int> qi;
qi.push(beg);
while (qi.size()) {
int cur = qi.front();
qi.pop();
if (!vis[cur])
continue;//非法点
if (cur == t)
return dis[cur];
for (int i = 0; i < vi[cur].size(); ++i) {
int node = vi[cur][i];
if (!vis[node] || dis[node] != INF)
continue;//
dis[node] = dis[cur] + 1;
qi.push(node);//
}
}
return -1;
}
void RevBfs(int beg) {//找出暂时的合法点
queue<int> qi;
qi.push(beg);
while (qi.size()) {
int cur = qi.front();
qi.pop();
if (vis[cur])
continue;//
vis[cur] = 1;//
for (int i = 0; i < revVi[cur].size(); ++i) {
int node = revVi[cur][i];
if (!vis[node])
qi.push(node);
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i) {
int x, y;
scanf("%d%d", &x, &y);
vi[x].push_back(y);
revVi[y].push_back(x);
}
scanf("%d%d", &s, &t);
RevBfs(t);
vector<int> tmp;
for (int i = 1; i <= n; ++i) {//对暂时的合法点进行剔除
if (!vis[i])
continue;//
for (int j = 0; j < vi[i].size(); ++j) {
if (!vis[vi[i][j]]) {//i的子节点有非法,导致i也是非法的
tmp.push_back(i);
// vis[i] = 0;//???为什么不能直接标记为0,而要先收集到tmp里面再整体标记
break;//优化
}
}
}
while (tmp.size()) {
int x = tmp.back();
// if (vis[x])
// puts("666");
vis[x] = 0;
tmp.pop_back();
}
printf("%d\n", Bfs(s));
}