AtCoder Beginner Contest 211- Number of Shortest paths
求最短路径的数量
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7,N=1e6+7;
int head[N],ne[N],e[N],cnt,dis[N],con[N],vis[N];
void add(int a,int b){
ne[cnt]=head[a],e[cnt]=b,head[a]=cnt++;
}
void bfs()
{
memset(dis,0x3f3f3f3f,sizeof dis);
con[1]=1;
dis[1]=0;
queue<int> q;
q.push(1);
while(!q.empty()){
int u=q.front(); q.pop();
if(vis[u]) continue;
vis[u]=1;
for(int i=head[u];i!=-1;i=ne[i]){
int j=e[i];
if(dis[j]>dis[u]+1){
dis[j]=dis[u]+1;
con[j]=con[u];
q.push(j);
}else if(dis[j]==dis[u]+1){
con[j]=(con[j]+con[u])%mod;
}
}
}
}
int main()
{
int n,m;
cin>>n>>m;
memset(head,-1,sizeof head);
for(int i=1;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
add(a,b),add(b,a);
}
bfs();
printf("%d\n",con[n]);
}
ZOJ1005 Jugs
现有容量为 C a Ca Ca的壶 A A A和容量为 C b Cb Cb的壶 B B B,需要往壶 B B B中倒入容量为 N N N的水。每次可以对水壶进行以下操作:
1、fill A/B 把壶 A A A或壶 B B B灌满水
2、empty A/B 把壶 A A A或壶 B B B置空
3、pour A B把壶 A A A中的水倒入壶 B B B中(壶 A A A中的水全倒完或壶 B B B被倒满)pour B A同理
请输出可以完成上述任务具体的操作步骤。
BFS–>队列–>初始情况入队–>只要队列非空,访问队首元素–>将队首元素的可能发展情况入队
参考文章
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
const int INF=0x3f3f3f3f;
typedef long long ll;
const int mod=1e9+7;
int a,b,n;
pair<int,int>jug;//a,b;
queue<pair<int,int> >q;
map<pair<int,int> ,string>path;
void bfs(){
//多组输入,注意每次初始化!!!
path.clear();
path[{0,0}]="";
while(!q.empty()){
q.pop();
}
q.push({0,0});//初始情况入队
while(!q.empty()){
if(q.front().second==n){//完成任务,壶B中灌入容量为n的水
//output
string ans=path[q.front()];
for(int i=0;i<ans.size();i++){
char ch=ans[i];
if(ch=='1') puts("fill A");
else if(ch=='2') puts("fill B");
else if(ch=='3') puts("empty A");
else if(ch=='4') puts("empty B");
else if(ch=='5') puts("pour A B");
else if(ch=='6') puts("pour B A");
}
puts("success");
return;
}
pair<int,int>top=q.front();
q.pop();
int ca=top.first;
int cb=top.second;
//分析所有可能的发展状态
if(ca<a&&path.count({a,cb})==0){
q.push({a,cb});
path[{a,cb}]=path[top]+'1';
}
if(cb<b&&path.count({ca,b})==0){
q.push({ca,b});
path[{ca,b}]=path[top]+'2';
}
if(ca>0&&path.count({0,cb})==0){
q.push({0,cb});
path[{0,cb}]=path[top]+'3';
}
if(cb>0&&path.count({ca,0})==0){
q.push({ca,0});
path[{ca,0}]=path[top]+'4';
}
if(ca>0&&cb<b){
int tmp=min(ca,b-cb);
if(path.count({ca-tmp,cb+tmp})==0){
q.push({ca-tmp,cb+tmp});
path[{ca-tmp,cb+tmp}]=path[top]+'5';
}
}
if(cb>0&&ca<a){
int tmp=min(cb,b-ca);
if(path.count({ca+tmp,cb-tmp})==0){
q.push({ca-tmp,cb+tmp});
path[{ca+tmp,cb-tmp}]=path[top]+'6';
}
}
}
}
int main(){
while(cin>>a>>b>>n){
bfs();
}
return 0;
}