【三月】第二次课堂练习
P1331
#include<bits/stdc++.h> using namespace std; char ch[1001][1001]; int n,m,s; int dx[5]={0,1,-1,0,0}; int dy[5]={0,0,0,1,-1}; int maxx,minx,maxy,miny; inline void dfs(int x,int y) { int sx,sy; if(x>maxx) maxx=x; else if(x<minx) minx=x; if(y>maxy) maxy=y; else if(y<miny) miny=y; for(int i=1;i<=4;i++) { sx=x+dx[i]; sy=y+dy[i]; if(ch[sx][sy]=='#') { ch[sx][sy]='.'; s++; dfs(sx,sy); } } } int main() { int ans=0; scanf("%d %d",&n,&m); char str[1001]; for(int i=1;i<=n;i++){ scanf("%s",str); for(int j=1;j<=m;j++) ch[i][j] = str[j-1]; } for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(ch[i][j]=='#') { ch[i][j]='.'; maxx=i;minx=i; maxy=j;miny=j; s=1; dfs(i,j); if((maxx-minx+1)*(maxy-miny+1)==s) ans++; else { printf("Bad placement."); return 0; } } } } printf("There are %d ships.",ans); return 0; }
P1141
#include<stdio.h> int m,n; int map[1001][1001]; int vis[1001][1001]; int numbers; int p[1000001][2]; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; int ans[1001][1001]; void dfs(int x,int y ){ numbers++; vis[x][y]=1; p[numbers][0]=x; p[numbers][1]=y; for(int i=0;i<4;i++){ int next_x=x+dx[i]; int next_y=y+dy[i]; if(next_x<1 || next_x>n || next_y<1 ||next_y>n) continue; if(vis[next_x][next_y] == 1) continue; if(map[next_x][next_y] == map[x][y]) continue; dfs(next_x,next_y); } } int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++){ char str[1001]; scanf("%s",str); for(int j=1;j<=n;j++) map[i][j]=str[j-1]; } for(int i=1;i<=m;i++){ int start_x,start_y; scanf("%d%d",&start_x,&start_y); if(ans[start_x][start_y]!=0) { printf("%d\n",ans[start_x][start_y]); } else{ numbers=0; dfs(start_x,start_y); for(int j=1;j<=numbers;j++){ int p_x = p[j][0]; int p_y = p[j][1]; ans[p_x][p_y] = numbers; } printf("%d\n",numbers); } } }
P1219
#include <stdio.h> #include <string.h> #include <stdlib.h> int n; int a[100]; int visited[3][100]; int count=0; void dfs(int step){ int i,j; if(step==n+1){ count++; if(count<=3){ for(i=1;i<=n;i++) printf("%d ",a[i]); printf("\n"); } return; } for(i=1;i<=n;i++){ if(!visited[0][i]&&!visited[1][i+step]&&!visited[2][step-i+n]){ visited[0][i]=visited[1][i+step]=visited[2][step-i+n]=1; a[step]=i; dfs(step+1); visited[0][i]=visited[1][i+step]=visited[2][step-i+n]=0; } } } int main(){ memset(visited,0,sizeof(visited)); scanf("%d",&n); dfs(1); printf("%d\n",count); return 0; }
P2404
#include<cstdio> #include<iostream> #include<cstdlib> using namespace std; int a[10001]={1},n; int print(int t) { for(int i=1;i<=t-1;i++)//输出一种拆分方案 { printf("%d+",a[i]); } printf("%d\n",a[t]); } int search(int s,int t) { int i; for(i=a[t-1];i<=s;i++) if(i<n)//当前数i要大于等于前一位数,且不超过n { a[t]=i;//保存当前拆分的数i s-=i;//s减去数i,s的值将继续拆分 if(s==0)print(t);//当s=0时,拆分结束输出结果 else search(s,t+1);//当s>0时,继续递归 s+=i;//回溯:加上拆分的数,以便产生所有可能的拆分 } } int main() { scanf("%d",&n); search(n,1);//将要拆分的数n传递给s return 0; }