递归与回溯 作业
poj1664
代码
#include<stdio.h>
int cal(int m,int n)
{
if(m==0||n==1)return 1;
if(n>m){
return cal(m,n-1);
}
else{
return cal(m-n,n)+cal(m,n-1);
}
}
int main()
{
int n,m;
int t;
scanf("%d",&t);
while(t)
{
t--;
scanf("%d%d",&m,&n);
printf("%d\n",cal(m,n));
}
}
poj2013
思路:第一个直接输出,第二个放到最后面,第三个放到最前面,第四个从后往前放,第五个从前往后放...按照名字个数为偶数和奇数分开解答。
代码
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void printlistodd(vector<string> sl)
{
vector<string> sl0;
if(sl.size()==1)
{
cout<<sl[0]<<endl;
}
else if (sl.size()%2==1){
sl0.push_back(sl[0]);
sl.erase(sl.begin());
printlistodd(sl0);
printlistodd(sl);
}
else{
sl0.push_back(sl[0]);
sl.erase(sl.begin());
printlistodd(sl);
printlistodd(sl0);
}
}
void printlisteven(vector<string> sl)
{
vector<string> sl0;
if(sl.size()==1)
{
cout<<sl[0]<<endl;
}
else if (sl.size()%2==0){
sl0.push_back(sl[0]);
sl.erase(sl.begin());
printlisteven(sl0);
printlisteven(sl);
}
else{
sl0.push_back(sl[0]);
sl.erase(sl.begin());
printlisteven(sl);
printlisteven(sl0);
}
}
void printfirst(vector<string> sl)
{
int l = sl.size();
cout<<sl[0]<<endl;
sl.erase(sl.begin());
if(l==1) return;
else if(l%2==1)printlistodd(sl);
else printlisteven(sl);
}
int main()
{
int t,n,n_max;
n=0;
vector<string> st;
string tmp;
char s[30];
while(scanf("%d",&t)&&t){
n++;
st.clear();
while(t){
t--;
scanf("%s",&s);
tmp=string(s);
st.push_back(tmp);
}
printf("SET %d\n",n);
printfirst(st);
}
return 0;
}
poj1979
注意读取单个字符的话要记得读去每一行的回车。
代码
#include<stdio.h>
#include<string.h>
int map[21][21];
int visited[21][21];
int W,H;
int ans;
void move(int x,int y){
if(x<0||x>H-1||y<0||y>W-1||map[x][y]=='#'||visited[x][y]){
//printf("???");
return ;
}
else{
//printf("哈?");
visited[x][y]=1;
ans++;
}
move(x-1,y);
move(x+1,y);
move(x,y-1);
move(x,y+1);
}
int main()
{
int i,j;
int x,y;
while(scanf("%d%d",&W,&H)&&W&&H){
memset(map,0,sizeof(map));
memset(visited,0,sizeof(visited));
ans = 0;
for(j=0;j<H;j++){
getchar(); //读走回车
for(i=0;i<W;i++){
scanf("%c",&map[j][i]);
//printf("j=%d,i=%d ",j,i);
if(map[j][i]=='@'){
x = j;
y = i;
//printf("x=%d,y=%d",x,y);
}
}
}
move(x,y);
printf("%d\n",ans);
}
return 0;
}
STAY. you have NO WHERE TO GO. try to live it well. for you have only ONE life.