title: ACM-DFS-Practice
tags:

  • ACM
  • DFS
    abbrlink: 7a871ff6
    date: 2020-11-17 17:53:56

部分和问题

给定整数a1,a2…,an,判断是否可以从中选出若干数,使他们的和恰好为k

  1. #include<iostream>
  2. #include<cstdio>
  3. using namespace std;
  4. const int maxn=20 + 5;
  5. int a[maxn],n,k;
  6. bool dfs(int i,int sum)
  7. {
  8. if(i==n) return sum == k;
  9. if(dfs(i+1, sum)) return true;
  10. if(dfs(i+1, sum+a[i])) return true;
  11. return false;
  12. }
  13. int main(){
  14. cin>>n;
  15. for(int i=0;i<n;i++)
  16. {
  17. cin>>a[i];
  18. }
  19. cin>>k;
  20. if(dfs(0,0)) cout<<"Yes"<<endl;
  21. else cout<<"No"<<endl;
  22. return 0;
  23. }

Lake Counting(POJ2386)

  1. #include<iostream>
  2. #include<cstdio>
  3. using namespace std;
  4. const int maxn = 100 + 5;
  5. int N,M;
  6. char f[maxn][maxn];
  7. void dfs(int x, int y)
  8. {
  9. f[x][y]='.';
  10. for(int dx=-1;dx<=1;dx++)
  11. for(int dy=-1;dy<=1;dy++)
  12. {
  13. int nx=x+dx, ny=y+dy;
  14. if(0 <= nx && nx < N && 0<=ny && ny< M && f[nx][ny]=='W')
  15. dfs(nx,ny);
  16. }
  17. return;
  18. }
  19. void solve()
  20. {
  21. int res=0;
  22. for(int i=0;i<N;i++)
  23. {
  24. for(int j=0;j<M;j++)
  25. {
  26. if(f[i][j]=='W')
  27. {
  28. dfs(i, j);
  29. res++;
  30. }
  31. }
  32. }
  33. cout<<res<<endl;
  34. }
  35. int main(){
  36. cin>>N>>M;
  37. for(int i=0;i<N;i++)
  38. for(int j=0;j<M;j++)
  39. cin>>f[i][j];
  40. solve();
  41. return 1;
  42. }