题目地址:HDU 1827
先缩点,缩完点后,找出入度为0的块就是需要传递的块。然后用块中花费最少的来当代表块中的花费。累加起来就行了。
代码如下:
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
using namespace std;
#define LL __int64
#define pi acos(-1.0)
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
const double eqs=1e-9;
const int MAXN=1000+10;
const int MAXM=2000+10;
int head[MAXN], cnt, indx, top, ans;
int low[MAXN], dfn[MAXN], belong[MAXN], instack[MAXN], stk[MAXN], cost[MAXN], d[MAXN], in[MAXN];
struct node
{
int u, v, next;
}edge[MAXM];
void add(int u, int v)
{
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void tarjan(int u)
{
low[u]=dfn[u]=++indx;
instack[u]=1;
stk[++top]=u;
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].v;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(instack[v]){
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u]){
ans++;
while(1){
int v=stk[top--];
instack[v]=0;
belong[v]=ans;
if(u==v) break;
}
}
}
void init()
{
memset(head,-1,sizeof(head));
memset(instack,0,sizeof(instack));
memset(dfn,0,sizeof(dfn));
memset(cost,INF,sizeof(cost));
memset(in,0,sizeof(in));
cnt=top=indx=ans=0;
}
int main()
{
int n, m, i, u, v, sum, tot;
while(scanf("%d%d",&n,&m)!=EOF){
init();
for(i=1;i<=n;i++){
scanf("%d",&d[i]);
}
while(m--){
scanf("%d%d",&u,&v);
add(u,v);
}
for(i=1;i<=n;i++){
if(!dfn[i]) tarjan(i);
}
//printf("ans=%d\n",ans);
for(i=0;i<cnt;i++){
if(belong[edge[i].u]!=belong[edge[i].v])
in[belong[edge[i].v]]++;
}
sum=tot=0;
for(i=1;i<=n;i++){
if(cost[belong[i]]>d[i])
cost[belong[i]]=d[i];
}
for(i=1;i<=ans;i++){
if(!in[i]){
tot++;
sum+=cost[i];
}
}
printf("%d %d\n",tot,sum);
}
return 0;
}