2020牛客寒假算法基础集训营1
两种写法
题意:
思路:
只用找到每个黑点,对于每个黑点来说看他的每个子树白色点的个数
路径有两种情况
1,黑点直接到白色点子树的路径
2,从白色点子树到黑点再到另一个白色子树的路径
代码:
两种写法
树上dp
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#include <stack>
#define Pll make_pair
#define PB push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
typedef long long ll;
const int MAXN=1e5+50;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int phi=1e9+6;
char ch[MAXN];
vector<int>p[MAXN];
ll dp[MAXN][3];//dp[i][0]经过i的子树有0个黑点
dp[i][1]经过i的子树有1个黑点
ll ans;
void dfs(int x,int fa){
if(ch[x]=='B'){
dp[x][1]=1;
dp[x][0]=0;
rep(i,0,p[x].size()-1){
int y=p[x][i];
if(y==fa)continue;
dfs(y,x);
ans+=dp[y][0]*dp[x][1];
dp[x][1]+=dp[y][0];
}
}
else{
dp[x][1]=0;
dp[x][0]=1;
rep(i,0,p[x].size()-1){
int y=p[x][i];
if(y==fa)continue;
dfs(y,x);
ans+=dp[y][1]*dp[x][0];
ans+=dp[x][1]*dp[y][0];
dp[x][1]+=dp[y][1];
dp[x][0]+=dp[y][0];
}
}
}
int main()
{
int n;
scanf("%d",&n);
scanf("%s",ch+1);
rep(i,1,n-1){
int u,v;
scanf("%d%d",&u,&v);
p[u].PB(v);
p[v].PB(u);
}
dfs(1,0);
printf("%lld\n",ans);
return 0;
}
/*
3
WBW
1 2
2 3
*/
第二种
直接找每个黑点的子树白色的个数,直接计算
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#include <stack>
#define Pll make_pair
#define PB push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
typedef long long ll;
const int MAXN=1e5+50;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int phi=1e9+6;
char ch[MAXN];
ll num;
vector<int>p[MAXN];
void dfs(int x,int fa){
if(ch[x]=='B')return;
num++;
rep(i,0,p[x].size()-1){
if(p[x][i]==fa)continue;
dfs(p[x][i],x);
}
}
int main()
{
int n;
scanf("%d",&n);
scanf("%s",ch+1);
rep(i,1,n-1){
int u,v;
scanf("%d%d",&u,&v);
p[u].PB(v);
p[v].PB(u);
}
ll ans=0;
rep(i,1,n){
ll sum=0;
if(ch[i]=='B'){
rep(j,0,p[i].size()-1){
num=0;
dfs(p[i][j],-1);
ans+=num;//黑点直接到白色点子树的路径
ans+=num*sum;//从白色点子树到黑点再到另一个白色子树的路径
sum+=num;
}
}
}
printf("%lld\n",ans);
return 0;
}
/*
3
WBW
1 2
2 3
*/