1060: [ZJOI2007]时态同步 - BZOJ

时间:2023-03-09 01:27:35
1060: [ZJOI2007]时态同步 - BZOJ

Description
小Q在电子工艺实习课上学习焊接电路板。一块电路板由若干个元件组成,我们不妨称之为节点,并将其用数字1,2,3….进行标号。电路板的各个节点由若干不相交的导线相连接,且对于电路板的任何两个节点,都存在且仅存在一条通路(通路指连接两个元件的导线序列)。在电路板上存在一个特殊的元件称为“激发器”。当激发器工作后,产生一个激励电流,通过导线传向每一个它所连接的节点。而中间节点接收到激励电流后,得到信息,并将该激励电流传向与它连接并且尚未接收到激励电流的节点。最终,激烈电流将到达一些“终止节点”——接收激励电流之后不再转发的节点。激励电流在导线上的传播是需要花费时间的,对于每条边e,激励电流通过它需要的时间为te,而节点接收到激励电流后的转发可以认为是在瞬间完成的。现在这块电路板要求每一个“终止节点”同时得到激励电路——即保持时态同步。由于当前的构造并不符合时态同步的要求,故需要通过改变连接线的构造。目前小Q有一个道具,使用一次该道具,可以使得激励电流通过某条连接导线的时间增加一个单位。请问小Q最少使用多少次道具才可使得所有的“终止节点”时态同步?
Input
第一行包含一个正整数N,表示电路板中节点的个数。 第二行包含一个整数S,为该电路板的激发器的编号。 接下来N-1行,每行三个整数a , b , t。表示该条导线连接节点a与节点b,且激励电流通过这条导线需要t个单位时间。
Output
仅包含一个整数V,为小Q最少使用的道具次数。
Sample Input
3
1
1 2 1
1 3 3
Sample Output
2
【数据规模】
对于40%的数据,N ≤ 1000
对于100%的数据,N ≤ 500000
对于所有的数据,te ≤ 1000000

其实题目是比较简单的,但是由于出题人标程打错了,爆了int,出题人除了ans开了long long,其他都是int,p党不好过呀,要么cheat,要么模拟C++爆int

把激发器做根,树dp

先算出每个节点往下延伸的最大深度,再把其他儿子调整成这个深度,这个可以证明是最优策略

要写BFS不然会爆栈的

原题本来是可以用这个过的

 {$M 5000000}
const
maxn=;
var
f:array[..maxn]of int64;
t:array[..maxn*]of int64;
first:array[..maxn]of longint;
next,last:array[..maxn*]of longint;
flag:array[..maxn]of boolean;
n,s,tot:longint;
ans:int64; procedure insert(x,y,z:longint);
begin
inc(tot);
last[tot]:=y;
next[tot]:=first[x];
first[x]:=tot;
t[tot]:=z;
end; procedure init;
var
i,x,y,z:longint;
begin
read(n,s);
for i:= to n- do
begin
read(x,y,z);
insert(x,y,z);
insert(y,x,z);
end;
end; procedure dfs(x:longint);
var
i:longint;
begin
i:=first[x];
flag[x]:=true;
while i<> do
begin
if flag[last[i]]=false then
begin
dfs(last[i]);
if f[x]<f[last[i]]+t[i] then f[x]:=f[last[i]]+t[i];
end;
i:=next[i];
end;
i:=first[x];
while i<> do
begin
if flag[last[i]]=false then inc(ans,f[x]-f[last[i]]-t[i]);
i:=next[i];
end;
flag[x]:=false;
end; begin
init;
dfs(s);
write(ans);
end.

但是没办法,用c++写了一个(爆int)

 #include<cstdio>
using namespace std; const int maxn=; int f[maxn],first[maxn],t[maxn*],next[maxn*],last[maxn*],fa[maxn];
bool flag[maxn];
int n,s,tot;
long long ans; void insert(int x,int y,int z)
{
++tot;
last[tot]=y;
next[tot]=first[x];
first[x]=tot;
t[tot]=z;
} void init()
{
int i,x,y,z;
scanf("%d%d",&n,&s);
for(i=;i<n;++i)
{
scanf("%d%d%d",&x,&y,&z);
insert(x,y,z);
insert(y,x,z);
}
} int q[maxn];
int head,tail; void bfs()
{
int i,j;
head=,tail=;
q[]=s;
for(i=;i<=n;++i)flag[i]=true;
while(head<=tail)
{
flag[q[head]]=false;
i=first[q[head]];
while(i!=)
{
if(flag[last[i]])q[++tail]=last[i];
else fa[q[head]]=last[i];
i=next[i];
}
++head;
}
for(i=tail;i>;i--)
{
j=first[q[i]];
while(j!=)
{
if(last[j]!=fa[q[i]] & f[q[i]]<f[last[j]]+t[j])f[q[i]]=f[last[j]]+t[j];
j=next[j];
}
j=first[q[i]];
while(j!=)
{
if(last[j]!=fa[q[i]])ans+=f[q[i]]-f[last[j]]-t[j];
j=next[j];
}
}
} int main()
{
init();
bfs();
printf("%lld",ans);
return ;
}