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 <cstdio> #include <cstring> #include <algorithm> #include <vector> #define maxn 1000 + 100 #define maxm 2000 + 200 #define INF 0x3f3f3f3f using namespace std; int n, m; struct node{ int u, v, next; }; int head[maxn], cnt; node edge[maxm]; int low[maxn], dfn[maxn]; int dfs_clock; int Stack[maxn], top; bool InStack[maxn]; int Belong[maxn]; int scc_clock; int cost[maxn];//通知每个人的花费 int in[maxn];//每个【缩点】的入度 vector<int>scc[maxn]; void init(){ cnt = 0; memset(head, -1, sizeof(head)); } void addedge(int u, int v){ edge[cnt] = {u, v, head[u]}; head[u] = cnt++; } void getmap(){ for(int i = 1; i <= n; ++i) scanf("%d", &cost[i]); while(m--){ int a, b; scanf("%d%d", &a, &b); addedge(a, b); } } void Tarjan(int u, int per){ int v; dfn[u] = low[u] = ++dfs_clock; Stack[top++] = u; InStack[u] = true; for(int i = head[u]; i != -1; i = edge[i].next){ v = edge[i].v; if(!dfn[v]){ Tarjan(v, u); low[u] = min(low[u], low[v]); } else if(InStack[v]){ low[u] = min(low[u], dfn[v]); } } if(dfn[u] == low[u]){ scc_clock++; scc[scc_clock].clear(); do{ v = Stack[--top]; InStack[v] = false; Belong[v] = scc_clock; scc[scc_clock].push_back(v); }while(v != u); } } void suodian(){//缩点 memset(in, 0, sizeof(in)); for(int i = 0; i < cnt; i++){ int u = Belong[edge[i].u]; int v = Belong[edge[i].v]; if(u != v) in[v]++; } } void find(){ memset(dfn, 0, sizeof(dfn)); memset(low, 0, sizeof(low)); memset(Stack, 0, sizeof(Stack)); memset(Belong, 0, sizeof(Belong)); memset(InStack, false, sizeof(InStack)); dfs_clock = scc_clock = top = 0; for(int i = 1; i <= n; ++i){//不是连通图 if(!dfn[i]) Tarjan(i, i); } } void solve(){ int ans = 0; int sum = 0; for(int i = 1; i <= scc_clock; ++i){ if(in[i] == 0){ //printf("--%d\n", i); ans++; int mins = INF; for(int j = 0; j < scc[i].size(); ++j) mins = min(mins, cost[scc[i][j]]); sum += mins; } } printf("%d %d\n", ans, sum); } int main (){ while(scanf("%d%d", &n, &m) != EOF){ init(); getmap(); find(); suodian(); solve(); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 1827--Summer Holiday【强连通缩点新建图】
原文地址:http://blog.csdn.net/hpuhjh/article/details/47777649