题解:P13359 [GDCPC 2024] 不等式
Heyg_future · · 题解
P13359 [GDCPC 2024] 不等式
题目
solution
呃,相信各位看到这个题都会想到差分约束,但是显然,本题差分约束看似不是那么可做,可能我太菜了,因为题目要求和最小,要证明起来很麻烦,因为每个数都有所约束,于是考虑拓扑排序。
对于每一个
证明。若某个
那么这就显而易见。将原来的不等式建立一张图,入度为
证明。若某个
那么结果显而易见,实现非常容易。我是这样做的。一张图存一个点的约束,另一个图用来跑图。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define LL long long
#define add(u,v,w) g[u].push_back({v,w})
#define ga(u,v) gg[u].push_back(v)
#define pr pair<LL,LL>
#define a first
#define b second
using namespace std ;
const LL N=2e5+500 ;
LL n,m,rd[N],f[N],ans,cd[N],vis ;
vector <pr> g[N] ;
vector <LL> gg[N] ;
queue <LL> q ;
void topo () {
for (LL i=1;i<=n;i++) {
if (!rd[i]) q.push (i),f[i]=1;
}
if (!q.size ()) {
cout<<-1 ;
return ;
}
LL u ;
while (q.size ()) {
u=q.front () ; q.pop () ;
vis++;
for (LL v:gg[u]) {
rd[v]--;
if (!rd[v]) q.push (v) ;
}
for (pr vi:g[u]) {
f[u]=max (f[u],f[vi.a]+f[vi.b]) ;
}
}
for (LL i=1;i<=n;i++) {
ans+=f[i] ;
if (!f[i]) ans ++ ;
}
if (ans<=1e9 && vis==n)
cout<<ans ;
else cout<<-1 ;
}
int main () {
cin>>n>>m ;
for (LL i=1,x,y,z;i<=m;i++) {
cin>>x>>y>>z ;
add (x,y,z) ;
ga (y,x) ;
ga (z,x) ;
rd[x]+=2 ;
}
topo () ;
return 0;
}
注意。
要开 long long。不然在判断和的时候可能会溢出。为了保险,可以在计算过程中判断溢出。
拓扑排序中有环是不可以的,所以统计每个点入队次数判环即可。
这样,即可通过此题。