ACM俱乐部算法基础练习赛(1)

时间:2023-03-08 15:39:13

A:

水题

代码:

 #include<cstdio>
#include<algorithm>
using namespace std; int she[]; int n,m,c; int main()
{
int ca=,a;
while(scanf("%d%d%d",&n,&m,&c)&&(n+m+c))
{
printf("Sequence %d\n",ca++);
for(int i=; i<=n; i++)
scanf("%d",&she[i]);
int ans=,ma=;
while(m--)
{
scanf("%d",&a);
ans+=she[a];
ma=max(ma,ans);
she[a]=-she[a];
}
if(ma>c)puts("Fuse was blown.");
else
{
puts("Fuse was not blown.");
printf("Maximal power consumption was %d amperes.\n",ma);
}
puts("");
}
return ;
}

B:

模拟;

代码:

 #include<cstdio>
#include<cstring>
#include<queue>
#define maxn 55
using namespace std; bool map[maxn][maxn]; int n,flag; struct node
{
int x,y;
}; queue<node>q; void move(char s)
{
node cur=q.back();
node next=q.front();
q.pop();
map[next.x][next.y]=;
if(s=='E')
{
next.x=cur.x;
next.y=cur.y+;
}
else if(s=='N')
{
next.x=cur.x-;
next.y=cur.y;
}
else if(s=='W')
{
next.x=cur.x;
next.y=cur.y-;
}
else if(s=='S')
{
next.x=cur.x+;
next.y=cur.y;
}
if(map[next.x][next.y]==)
{
flag=;
return;
}
else if(next.x<=||next.x>||next.y<=||next.y>)
{
flag=-;
return;
}
else
{
q.push(next);
map[next.x][next.y]=;
}
} char s[];
int main()
{
while(scanf("%d",&n)&&n)
{
node no;
flag=;
memset(map,,sizeof map);
while(!q.empty())q.pop();
for(int i=; i<=; i++)
{
no.x=;
no.y=i;
map[][i]=;
q.push(no);
}
scanf("%s",s);
int i;
for(i=; i<n; i++)
{
move(s[i]);
if(flag<)break;
}
if(flag==)printf("The worm successfully made all %d moves.\n",n);
else if(flag==-)printf("The worm ran off the board on move %d.\n",i+);
else if(flag==)printf("The worm ran into itself on move %d.\n",i+);
}
return ;
}

C:

我用的是bfs;

代码:

 #include<cstdio>
#include<queue>
#include<vector>
#define maxn 10005
using namespace std; vector<int>ve[maxn];
int di[maxn];
queue<int>q;
int main()
{
int n,x;
scanf("%d",&n);
for(int i=;i<=n;i++)
{
scanf("%d",&x);
ve[x].push_back(i);
}
int l=ve[].size();
for(int i=;i<l;i++)
{
q.push(ve[][i]);
di[ve[][i]]=;
}
while(!q.empty())
{
int cur=q.front();
q.pop();
l=ve[cur].size();
for(int i=;i<l;i++)
{
q.push(ve[cur][i]);
di[ve[cur][i]]=di[cur]+;
}
}
int ans=;
for(int i=;i<=n;i++)
if(ans<di[i])ans=di[i];
printf("%d\n",ans);
}

D:

dfs;

我先用一个表来存,一直都是T;

没想到用状态压缩就可以过了;

代码:

 #include<cstdio>
#include<vector>
#define maxn 23
using namespace std; vector<int>ve[maxn];
int n,s,m; bool dfs(int x,int t)
{
if(t==s)return x==n-;
int l=ve[x].size();
for(int i=;i<l;i++)
{
int a=ve[x][i];
if(~(t>>a)&)
if(dfs(a,t|(<<a)))
return ;
}
return ;
} int main()
{
int x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=;i<n;i++)
ve[i].clear();
for(int i=;i<m;i++)
{
scanf("%d%d",&x,&y);
x--,y--;
ve[x].push_back(y);
ve[y].push_back(x);
}
s=(<<n)-;
if(dfs(,))puts("");
else puts("");
}
return ;
}