题目:
题解:
1A纪念
先Tarjan缩点,找到所有入度为0的点,在这些强连通分量中分别找到最小的权值
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#define M 10005
#define N 10005
using namespace std;
int nxt[M*2],point[M*2],v[M*2],tot,tmp,n,m,NN,num;
int dfn[N],low[N],strack[N],x[N],y[N],in[N],belong[N],qz[N],ww[N];
bool vis[N];
void cl()
{
tot=0;num=0;tmp=0;NN=0;
memset(nxt,0,sizeof(nxt));
memset(point,0,sizeof(point));
memset(v,0,sizeof(v));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(strack,0,sizeof(strack));
memset(vis,0,sizeof(vis));
memset(in,0,sizeof(in));
memset(belong,0,sizeof(belong));
memset(qz,0x7f,sizeof(qz));
}
void addline(int x,int y)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;
}
void tarjan(int now)
{
dfn[now]=low[now]=++NN; vis[now]=1; strack[++tmp]=now;
for (int i=point[now];i;i=nxt[i])
if (!dfn[v[i]])
{
tarjan(v[i]);
low[now]=min(low[now],low[v[i]]);
}
else if (vis[v[i]]) low[now]=min(low[now],dfn[v[i]]);
if (dfn[now]==low[now])
{
num++;
while (strack[tmp]!=now)
{
belong[strack[tmp]]=num;
qz[num]=min(qz[num],ww[strack[tmp]]);
vis[strack[tmp]]=0; tmp--;
}
belong[strack[tmp]]=num;
qz[num]=min(qz[num],ww[strack[tmp]]);
vis[strack[tmp]]=0; tmp--;
}
}
int main()
{
int n,m,i;
while (~scanf("%d%d",&n,&m))
{
cl();
int ans1=0,ans2=0;
for (i=1;i<=n;i++)
scanf("%d",&ww[i]);
for (i=1;i<=m;i++)
{
scanf("%d%d",&x[i],&y[i]);
addline(x[i],y[i]);
}
for (i=1;i<=n;i++)
if (!dfn[i]) tarjan(i);
for (i=1;i<=m;i++)
if (belong[x[i]]!=belong[y[i]])
++in[belong[y[i]]];
for (i=1;i<=num;i++)
if (!in[i]) ans1++,ans2+=qz[i];
printf("%d %d\n",ans1,ans2);
}
}