已ac,但不明白
查看原帖
已ac,但不明白
1265349
HsNu1ly7_楼主2024/9/4 14:51

为什么我从点 11 开始 dfs 会 WA,从最后一个要保留的点,也就是 VkV_k 开始搜就 AC 了。

WA 代码

#include <bits/stdc++.h>
using namespace std ;
#define int long long
#define F(i , x , n) for (int i = x ; i <= n; i++)
#define umap unordered_map
#define uset unordered_set
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define frep freopen(".in","r",stdin);freopen(".out","w",stdout);

using u64 = unsigned long long ;

const int mod = 998244353 ;
const int CFMAXN = 2e5 + 10 ;
const int INF = 0x3f3f3f3f3f ;

vector <int> g[200010] ;
int n , k ;
int ans ;
int v[CFMAXN] , c[CFMAXN] ;
void dfs ( int u , int fa ){
	for ( auto p : g[u] ){
		if ( p == fa ) continue ;
		dfs ( p , u ) ;
		c[u] |= c[p] ;
	}
	if ( c[u] ) ++ans ;
}
void solve (){
	cin >> n >> k ;
	for (int i = 1; i < n ;i++){
		int u , w ;
		cin >> u >> w ;
		g[u].push_back ( w ) ;
		g[w].push_back(u);
	}
	for (int i = 1 ; i <= k ; i++){
		cin >> v[i] ;
		c[v[i]] = 1 ;
	}
	dfs ( 1 , 0 ) ;
	cout << ans ;
}

signed main (){
	int _ = 1 ;
	//cin >> _ ;
	while ( _-- ){
		solve () ;
	}
	return 0 ;
}

AC 代码

#include <bits/stdc++.h>
using namespace std ;
#define int long long
#define F(i , x , n) for (int i = x ; i <= n; i++)
#define umap unordered_map
#define uset unordered_set
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define frep freopen(".in","r",stdin);freopen(".out","w",stdout);

using u64 = unsigned long long ;

const int mod = 998244353 ;
const int CFMAXN = 2e5 + 10 ;
const int INF = 0x3f3f3f3f3f ;

int read(){int xttsbsb=0,fcsbsbsb=1; char chabbb=getchar(); while(chabbb<'0'||chabbb>'9'){if(chabbb=='-'){fcsbsbsb=-1; } chabbb=getchar(); } while(chabbb>='0'&&chabbb<='9'){xttsbsb=xttsbsb*10+(chabbb-'0'); chabbb=getchar(); } return xttsbsb*fcsbsbsb; }
void write(int x){if (x<0){putchar('-'); x=-x; } int stasbsb[68]={},topsbsbsb=0; do{stasbsb[topsbsbsb++]=x%10; x/=10; }while(x); while(topsbsbsb){putchar(stasbsb[--topsbsbsb]+48); } }
int qpow (int a,int b,int p){if ( a == 0 ){return 0;} if ( b == 0 ){return 1;} int res = 1 ; while ( b ){if (b&1){res *= a ; if (p) res %= p; } a *= a ; a %= ( (p == 0) ? (a + 1) : p ) ; b >>= 1 ; } return res % ( (p == 0) ? (a + 1) : p ); }

/*----------------template----------------------*/
vector <int> g[200010] ;
int n , k ;
int ans ;
int v[CFMAXN] , c[CFMAXN] ;
void dfs ( int u , int fa ){
	for ( auto p : g[u] ){
		if ( p == fa ) continue ;
		dfs ( p , u ) ;
		c[u] |= c[p] ;
	}
	if ( c[u] ) ++ans ;
}
void solve (){
	cin >> n >> k ;
	for (int i = 1; i < n ;i++){
		int u , w ;
		cin >> u >> w ;
		g[u].push_back ( w ) ;
		g[w].push_back(u);
	}
	int s ;
	for (int i = 1 ; i <= k ; i++){
		cin >> v[i] ;
		c[v[i]] = 1 ;
		s = v[i] ;
	}
	dfs ( s , 0 ) ;
	cout << ans ;
}

signed main (){
	int _ = 1 ;
	//cin >> _ ;
	while ( _-- ){
		solve () ;
	}
	return 0 ;
}
2024/9/4 14:51
加载中...