CF1677B Tokitsukaze and Meeting
做法
定义两个数组:
col[i] 代表这一列中学生编号模 余数是 的列是否是好的
row[i] 代表 学生进入后总计有多少行是好的
首先对于 col[i] 容易发现,对于每次进入的学生更新即可,因为一个模 是 的学生进入后,假如他是严肃的,那么这一列一直都会是好的。
对于 row[i],我们可以不断递推,当 进入后, 号学生会被挤到下一行,那么row[i] 就可以从 row[i-m] 转移过来,只用判断当前 号学生到 号学生中是否存在严肃的,如果是,就 row[i]=row[i-m]+1,判断一个区间是否有 ,可以用前缀和解决。
假如 的话,直接看当前 号学生是不是 即可,如果是,就 row[i]=1
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define fi first
#define se second
#define str string
#define YES cout<<"YES"<<'\n';
#define NO cout<<"NO"<<'\n';
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*f;
}
void write(int x)
{
if(x<0)
putchar('-'),x=-x;
if(x>9)
write(x/10);
putchar(x%10+'0');
return;
}
const ll INF=1e18;
const ll MAXN=1e6+5;
ll t,n,m;
ll pre[MAXN],row[MAXN],col[MAXN];
str s;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--){
cin>>n>>m;
cin>>s;
for(int i=0;i<=n*m;++i){
pre[i]=0;
row[i]=0;
col[i]=0;
}
for(int i=1;i<=n*m;++i){
pre[i]=pre[i-1];
if(s[i-1]=='1'){
pre[i]++;
}
}
ll curcol=0;
for(int i=1;i<=n*m;++i){
ll x=i%m;
if(s[i-1]=='1'&&!col[x]){
col[x]=1;
curcol++;
}
if(i<=m){
if(pre[i]>0){
row[i]=1;
}
}
else{
row[i]=row[i-m]+(pre[i]-pre[i-m]>0);
}
cout<<row[i]+curcol<<" ";
}
cout<<'\n';
}
return 0;
}CF1675F Vlad and Unfinished Business
做法
可以从 开始 ,容易算出有多少条边,是一定要走过去的。然后我们算出一共要经过多少条必要的边,数量记为 ,由于我们一定是要先走下去在走回去再走回来,那么就是 条边要走。然后我们还要从 从走到 ,所以最坏情况总和是 ,但是我们发现有一些 的路径上的边会和 条边重合,这些边也可以 一遍,然后最终的式子是 ,减两遍的原因是,我们的最短路径中和 条边中可以不走这些重合的边,因为你可以在一开始从 出发就走掉,这样在 条边中,就不用往回走,而在 中你也不用走这些边,因为一开始第一遍已经走到这里了。
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define fi first
#define se second
#define str string
#define YES cout<<"YES"<<'\n';
#define NO cout<<"NO"<<'\n';
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*f;
}
void write(int x)
{
if(x<0)
putchar('-'),x=-x;
if(x>9)
write(x/10);
putchar(x%10+'0');
return;
}
const ll INF=1e18;
const ll MAXN=2e5+5;
ll t,n,k,a[MAXN],x,y,dep[MAXN];
ll need[MAXN],fa[MAXN],cnt;
vector<ll> g[MAXN];
void dfs1(ll u,ll f){
fa[u]=f;
dep[u]=dep[f]+1;
for(ll v:g[u]){
if(v==f){
continue;
}
dfs1(v,u);
if(need[v]){
need[u]=1;
cnt++;
}
}
}
void solve(){
cin>>n>>k>>x>>y;
for(int i=1;i<=n;++i){
g[i].clear();
need[i]=0;
dep[i]=0;
fa[i]=0;
}
for(int i=1;i<=k;++i){
cin>>a[i];
need[a[i]]=1;
}
for(int i=1;i<n;++i){
ll u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
cnt=0;
dfs1(x,0);
ll same=0;
ll u=y;
while(u!=x){
if(need[u]){
same++;
}
u=fa[u];
}
ll dis=dep[y]-dep[x];
ll ans=2*cnt+dis-2*same;
cout<<ans<<'\n';
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--){
solve();
}
return 0;
}