标签:read sizeof 内存 push tar inline turn break 农夫
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
5 17
4
深搜 炸:
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int N=100010; bool vis[N]; int people; int milk; int answer=99999999; int nowans=0; inline int read() { int x=0;char c=getchar(); while(c<‘0‘||c>‘9‘)c=getchar(); while(c>=‘0‘&&c<=‘9‘)x=x*10+c-‘0‘,c=getchar(); return x; } void dfs(int nowpeople) { vis[nowpeople]=1; if(nowpeople==milk) { answer=min(answer,nowans); return ; } if(!vis[nowpeople+1]&&nowpeople+1>0&&nowpeople+1<=milk+1) { nowans++; vis[nowpeople+1]=1; dfs(nowpeople+1); nowans--; vis[nowpeople+1]=0; } if(!vis[nowpeople-1]&&nowpeople-1>0&&nowpeople-1<=milk+1) { nowans++; vis[nowpeople-1]=1; dfs(nowpeople-1); nowans--; vis[nowpeople-1]=0; } if(!vis[nowpeople*2]&&nowpeople*2>0&&nowpeople*2<=milk+1) { nowans++; vis[nowpeople*2]=1; dfs(nowpeople*2); nowans--; vis[nowpeople*2]=0; } } int main() { people=read(); milk=read(); dfs(people); printf("%d",answer); return 0; }
广搜:
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> #include<cstdlib> using namespace std; const int N=100010; struct node{ int x,step; }now,nxt,top; int peo,milk; bool vis[N]; queue<node>q; inline int read() { int x=0;char c=getchar(); while(c<‘0‘||c>‘9‘)c=getchar(); while(c>=‘0‘&&c<=‘9‘)x=x*10+c-‘0‘,c=getchar(); return x; } inline void bfs(int start) { now.x=start; now.step=0; q.push(now); while(!q.empty()) { top=q.front(); q.pop(); int x=top.x; if(x==milk) { printf("%d\n",top.step); exit(0); } if(x+1>0&&x+1<=milk+1&&!vis[x+1]) { vis[x+1]=1; nxt.x=x+1; nxt.step=top.step+1; q.push(nxt); } if(x-1>=0&&x-1<=milk+1&&!vis[x-1]) { vis[x-1]=1; nxt.x=x-1; nxt.step=top.step+1; q.push(nxt); } if(x*2>=0&&x*2<=milk+1&&!vis[x*2]) { vis[x*2]=1; nxt.x=x*2; nxt.step=top.step+1; q.push(nxt); } } } int main() { peo=read(); milk=read(); bfs(peo); return 0; }
简单:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; int a[100001],b[100001],c[100001]; int tot=0; int print(int d) { if(c[d]!=0) print(c[d]); tot++; } int main() { memset(b,0,sizeof(b)); memset(a,0,sizeof(a)); int n,k,x; cin>>n>>k; if(n==k) { cout<<0<<endl; return 0; } a[1]=n; b[n]=1; int head=0,tail=1; while(head!=tail) { head++; for(int i=1; i<=3; ++i) { if(i==1) x=a[head]+1; if(i==2) x=a[head]-1; if(i==3) x=a[head]*2; if(x>=0&&b[x]==0&&x<=100000) { tail++; a[tail]=x; c[tail]=head; if(x==k) { print(tail); cout<<tot-1<<endl; head=tail; break; } b[x]=1; } } } }
标签:read sizeof 内存 push tar inline turn break 农夫
原文地址:http://www.cnblogs.com/lyqlyq/p/7074524.html