看着这道题给人感觉就是tarjan求SCC,然而还得判断是否能控制全部间谍,这就得先从可以贿赂的点dfs一遍。
如果没有全部被标记了,就输出NO,再从没被标记的点里找最小的标号。
如果全被标记,就输出YES,再从入度为0的缩点里找最小的价格,加到ans中,最后输出ans。
——代码
#include <cstdio>
#include <stack>
#include <cstring> using namespace std; int n, p, r1, cnt, idx, ans = , minn;
int a[], next[], to[], head[], low[], dfn[], belong[], r[];
bool ins[], vis[], mey[];
stack <int> s; inline void add(int x, int y)
{
to[cnt] = y;
next[cnt] = head[x];
head[x] = cnt++;
} void dfs(int u)
{
int i, v;
vis[u] = ;
mey[u] = ;
for(i = head[u]; i != -; i = next[i])
{
v = to[i];
if(!vis[v]) dfs(v);
}
} void tarjan(int u)
{
low[u] = dfn[u] = ++idx;
s.push(u);
ins[u] = ;
int i, v;
for(i = head[u]; i != -; i = next[i])
{
v = to[i];
if(!dfn[v])
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(ins[v]) low[u] = min(low[u], dfn[v]);
}
if(low[u] == dfn[u])
{
cnt++;
do
{
v = s.top();
s.pop();
ins[v] = ;
belong[v] = cnt;
}while(u != v);
}
} int main()
{
int i, j, k, x, y, u, v;
scanf("%d %d", &n, &p);
for(i = ; i <= p; i++)
{
scanf("%d", &x);
scanf("%d", &a[x]);
}
memset(head, -, sizeof(head));
scanf("%d", &r1);
for(i = ; i <= r1; i++)
{
scanf("%d %d", &x, &y);
add(x, y);
}
for(i = ; i <= n; i++)
if(!vis[i] && a[i])
dfs(i);
for(i = ; i <= n; i++)
if(!mey[i])
ans = min(ans, i);
if(ans != )
{
printf("NO\n%d", ans);
return ;
}
cnt = ;
for(i = ; i <= n; i++)
if(!dfn[i])
tarjan(i);
for(u = ; u <= n; u++)
for(i = head[u]; i != -; i = next[i])
{
v = to[i];
if(belong[u] != belong[v]) r[belong[v]]++;
}
ans = ;
for(i = ; i <= cnt; i++)
if(r[i] == )
{
minn = ;
for(j = ; j <= n; j++)
if(belong[j] == i && a[j])
minn = min(minn, a[j]);
ans += minn;
}
printf("YES\n%d", ans);
return ;
}