12 16 2 2 2 2 2 2 2 2 2 2 2 2 1 3 3 2 2 1 3 4 2 4 3 5 5 4 4 6 6 4 7 4 7 12 7 8 8 7 8 9 10 9 11 10
3 6
强连通缩点,然后把缩点后的图,求入度为零的点,在这些点里面求最小花费。
刚开始竟然把栈定义在函数里面了,我说怎么一直不对!!
#include"stdio.h" #include"string.h" #include"stack" using namespace std; #define N 1005 #define min(a,b) (a<b?a:b) const int inf=10000000; int head[N],dfn[N],low[N],belong[N]; int t,n,index,bcnt,val[N],mark[N]; stack<int>s; struct node { int v,next; }e[N*3]; void add(int u,int v) { e[t].v=v; e[t].next=head[u]; head[u]=t++; } void tarjan(int u) { int i,v; dfn[u]=low[u]=++index; mark[u]=1; s.push(u); for(i=head[u];i!=-1;i=e[i].next) { v=e[i].v; if(!dfn[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(mark[v]) { low[u]=min(low[u],dfn[v]); } } if(dfn[u]==low[u]) { bcnt++; do { v=s.top(); s.pop(); mark[v]=0; belong[v]=bcnt; }while(u!=v); } } void solve() { int i; index=bcnt=0; memset(dfn,0,sizeof(dfn)); for(i=1;i<=n;i++) { if(!dfn[i]) tarjan(i); } } void work() { int i,j,u,v,t,ans; int in[N]; memset(in,0,sizeof(in)); for(i=1;i<=n;i++) { u=belong[i]; for(j=head[i];j!=-1;j=e[j].next) { v=belong[e[j].v]; if(u!=v) in[v]++; } } t=ans=0; for(i=1;i<=bcnt;i++) { if(in[i]==0) { int tmp=inf; for(j=1;j<=n;j++) { if(belong[j]==i) tmp=min(tmp,val[j]); } ans+=tmp; t++; } } printf("%d %d\n",t,ans); } int main() { int i,m,u,v; while(~scanf("%d%d",&n,&m)) { for(i=1;i<=n;i++) scanf("%d",&val[i]); t=0; memset(head,-1,sizeof(head)); while(m--) { scanf("%d%d",&u,&v); add(u,v); } solve(); work(); } return 0; }
</pre>模拟栈稍微快一点:<span style="font-family:Tahoma; background-color:rgb(215,235,255)">140MS</span><p></p><p><span style="font-size:18px"></span></p><pre code_snippet_id="444038" snippet_file_name="blog_20140806_3_9248279" name="code" class="cpp">void tarjan(int u) { int i,v; dfn[u]=low[u]=++index; //注意先自加一再赋值 instack[u]=true; stap[++stop]=u; //同上 for(i=head[u];i!=-1;i=e[i].next) { v=e[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(dfn[u]==low[u]) { bcnt++; do { v=stap[stop--]; instack[v]=false; belong[v]=bcnt; }while(u!=v); } }
hdu 1827 Summer Holiday (强连通分量),布布扣,bubuko.com
hdu 1827 Summer Holiday (强连通分量)
原文:http://blog.csdn.net/u011721440/article/details/38401607