2.1.4_深搜
//@auther Yang Zongjun
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 25;
const int INF = 2100000000;
int n, a[MAXN], sum;
//已经从前i项得到了和tot,然后对于i项之后的进行分支
bool dfs(int i, int tot)
{
//如果前i项都计算过了,则返回tot与sum是否相等
if(i == n) return sum == tot;
//不加上a[i]的情况
if(dfs(i + 1, tot)) return true;
//加上a[i]的情况
if(dfs(i + 1, tot + a[i])) return true;
//无论是否加入a[i]都不能凑成sum就返回false
return false;
}
void solve()
{
if(dfs(0, 0)) printf("yes\n");
else printf("no\n");
}
int main()
{
freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
while(~scanf("%d", &n))
{
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
scanf("%d", &sum);
solve();
}
return 0;
}
poj2386 找水滩问题
//@auther Yang Zongjun
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 105;
const int INF = 2100000000;
int n, m;
char maze[MAXN][MAXN];
void dfs(int x, int y)
{
maze[x][y] = '.';
for(int i = -1; i <= 1; i++)
{
for(int j = -1; j <= 1; j++)
{
int nx = x + i, ny = y + j;
if((0 <= nx && nx < n) &&(0 <= ny && ny < m) && maze[nx][ny] == 'W')
{
dfs(nx, ny);
}
}
}
}
int main()
{
//freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
cin >> n >> m;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> maze[i][j];
//cout << maze[i][j];
}
//cout << endl;
}
//cout << n << m <<endl;
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(maze[i][j] == 'W')
{
dfs(i, j);
ans++;
}
}
}
cout << ans << endl;
return 0;
}
此题也可这样写:
//@auther Yang Zongjun
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 105;
const int INF = 2100000000;
int n, m;
char maze[MAXN][MAXN];
int dir[][2] = {{-1,0},{-1,-1},{-1,1},{0,1},{0,-1},{1,0},{1,-1},{1,1} };
void dfs(int x, int y)
{
maze[x][y] = '.';
/*for(int i = -1; i <= 1; i++)
{
for(int j = -1; j <= 1; j++)
{
int nx = x + i, ny = y + j;
if((0 <= nx && nx < n) &&(0 <= ny && ny < m) && maze[nx][ny] == 'W')
{
dfs(nx, ny);
}
}
}*/
//或者这样写
for(int i = 0; i < 8; i++)
{
int nx = x + dir[i][0], ny = y + dir[i][1];
if((0 <= nx && nx < n) &&(0 <= ny && ny < m) && maze[nx][ny] == 'W')
{
dfs(nx, ny);
}
}
}
int main()
{
freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
cin >> n >> m;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> maze[i][j];
//cout << maze[i][j];
}
//cout << endl;
}
//cout << n << m <<endl;
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(maze[i][j] == 'W')
{
dfs(i, j);
ans++;
}
}
}
cout << ans << endl;
return 0;
}