L2-013 Red Alert (DFS+Stain)

topic link

https://pintia.cn/problem-sets/994805046380707840/problems/994805063963230208

ideas

For each city we have a overmarker over[i]=truefor the iii cities have been captured. After each city is captured, we mark it astrueand mark all its connected cities astrue(actually a graph traversal), and then each time we take the pre-capture and capture After comparing the number of connected blocks, if it is found that the number of connected blocks has increased (excluding the city that was captured), then the country is divided, so we output,Red Alert: City k is lost!otherwise we only need to outputity k is lost., and finally if the number of captured cities fornnIf n , the final outputGame Over.

code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

const int N = 5e2+10;

bool mp[N][N];
bool vis[N],over[N];
int n,m;

void dfs(int u){
    
    
	if(vis[u]) return;
	vis[u] = true;
	for(int i = 0;i < n; ++i) {
    
    
		if(i != u && mp[u][i] && !over[i])
			dfs(i);
	}
}

int get_num(){
    
    
	int ans = 0;
	memset(vis,false,sizeof vis);
	for(int i = 0;i < n; ++i) {
    
    
		if(!vis[i] && !over[i]){
    
    
			dfs(i);
			ans++;
		}
	}
	return ans;
}

int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m;
	int u,v;
	for(int i = 1;i <= m; ++i) {
    
    
		cin>>u>>v;
		mp[u][v] = mp[v][u] = true;
	}
	int k,t,num = get_num();
	cin>>k;
	for(int i = 1;i <= k; ++i) {
    
    
		cin>>t;
		over[t] = true;
		int loc = get_num();
		if(loc > num) {
    
    	
			cout<<"Red Alert: City "<<t<<" is lost!"<<endl;
		} else {
    
    
			cout<<"City "<<t<<" is lost."<<endl;
		}
		num = loc;
			
	}
	if(k == n) cout<<"Game Over."<<endl;
	
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46201544/article/details/123937521
Recommended