天梯赛题目红色警戒,是一个图的连通性问题,大概可以考虑dfs邻接矩阵,dfs邻接表vector,并查集三种思路
#include <bits/stdc++.h>
using namespace std;
int a[1000][1000],n,sum=0,m;
int vis[55000];
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void dfs(int s)
{
vis[s]=1;
for(int i=0;i<n;i++)
{
if(a[s][i]!=INT_MAX)
{
if(!vis[i])
{
dfs(i);
}
}
}
}
int main(int argc, char** argv) {
int i,j,x,y,t,lost[55000],edge[55000],edg[55000];
cin>>n>>m;
fill(a[0],a[0]+1000*1000,INT_MAX);
memset(vis,0,sizeof(vis));
memset(lost,0,sizeof(lost));
for(i=0;i<m;i++)
{
cin>>x;
cin>>y;
edge[i]=x;
edg[i]=y;
a[x][y]=1;
a[y][x]=1;
}
int cnt=0;
for(i=0;i<n;i++)
{
if(!vis[i])
{
dfs(i);
cnt++;
}
}
cin>>t;
for(i=0;i<t;i++)
{
cin>>x;
int h=x;
lost[x]=1;
fill(a[0],a[0]+1000*1000,INT_MAX);
for(j=0;j<m;j++)
{
if(lost[edge[j]]!=1&&lost[edg[j]]!=1)
{
x=edge[j];
y=edg[j];
a[x][y]=1;
a[y][x]=1;
}
}
memset(vis,0,sizeof(vis));
int cn=0;
for(j=0;j<n;j++)
{
if(!vis[j])
{
dfs(j);
cn++;
}
}
if(cn==cnt+1||cn==cnt)
{
printf("City %d is lost.\n",h);
}
else{
printf("Red Alert: City %d is lost!\n",h);
}
cnt=cn;
}
if(t==n)
{
cout<<"Game Over."<<endl;
}
return 0;
}
上面是通过邻接矩阵实现的dfs,下面通过邻接表vector实现
#include <bits/stdc++.h>
using namespace std;
vector<int> a[550];
int n,sum=0,m;
int vis[550];
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void dfs(int s)
{
vis[s]=1;
for(int i=0;i<a[s].size();i++)
{
if(!vis[a[s][i]])
{
dfs(a[s][i]);
}
}
}
int main(int argc, char** argv) {
int i,j,x,y,t,lost[550],edge[550],edg[550];
cin>>n>>m;
for(i=0;i<550;i++)
{
a[i].clear();
}
memset(vis,0,sizeof(vis));
memset(lost,0,sizeof(lost));
for(i=0;i<m;i++)
{
cin>>x;
cin>>y;
edge[i]=x;
edg[i]=y;
a[x].push_back(y);
a[y].push_back(x);
}
int cnt=0;
for(i=0;i<n;i++)
{
if(!vis[i])
{
dfs(i);
cnt++;
}
}
cin>>t;
for(i=0;i<t;i++)
{
cin>>x;
int h=x;
lost[x]=1;
for(j=0;j<550;j++)
{
a[j].clear();
}
for(j=0;j<m;j++)
{
if(lost[edge[j]]!=1&&lost[edg[j]]!=1)
{
x=edge[j];
y=edg[j];
a[x].push_back(y);
a[y].push_back(x);
}
}
memset(vis,0,sizeof(vis));
int cn=0;
for(j=0;j<n;j++)
{
if(!vis[j])
{
dfs(j);
cn++;
}
}
if(cn==cnt+1||cn==cnt)
{
printf("City %d is lost.\n",h);
}
else{
printf("Red Alert: City %d is lost!\n",h);
}
cnt=cn;
}
if(t==n)
{
cout<<"Game Over."<<endl;
}
return 0;
}