dfstu
quoc14
c_cpp
a month ago
1.8 kB
1
Indexable
Never
caidat
#include <iostream> using namespace std; int n; int a[1002][1002]; int w[1002]; int hascycle; int vs[1003]; int parent[1003]; int ans; void memm() { for (int i=0; i<=1000; i++) { w[1002] = 0; for (int j=0; j<=1000; j++) a[i][j] = 0; } } int breakcycle(int dau, int cuoi) { int v1 = dau; int v2 = cuoi; int minn = a[v1][v2]; int cur = cuoi; while (parent[cur] != -1) { if (a[cur][parent[cur]] < minn) { minn = a[cur][parent[cur]]; v1 = cur; v2 = parent[cur]; } cur = parent[cur]; } a[v1][v2] = 0; a[v2][v1] = 0; return minn; } void resetvs(){ for (int i = 1; i<=1000; i++) { vs[i] = 0; parent[i] = -1; } } void DFS(int start, int i, int pre) { //cout << pre << " " << i << endl; vs[i] = 1; parent[i] = pre; if (hascycle == 1) return; for (int j = 0; j<n; j++) if (j != pre) { if (hascycle == 1) return; if (a[i][j] != 0 && vs[j] == 0) { DFS(start, j,i); } else if (a[i][j] != 0 && vs[j] == 1 && j == start) { ans += breakcycle(start, i); hascycle = 1; return; } } //vs[i] = 0; } int main() { freopen("Text.txt","r",stdin); int ntc; cin >> ntc; for (int tc=1; tc<=ntc; tc++) { memm(); cin >> n; for (int k = 0; k < n; k++){ int id, ntl; cin >> id; cin >> w[id]; cin >> ntl; for (int i = 1; i <=ntl; i++) { int v; cin >> v; a[id][v] = 1; a[v][id] = 1; } } for (int i = 0; i<n; i++) for (int j=0; j<n; j++) if (a[i][j] == 1) a[i][j] = w[i] + w[j]; ans = 0; for (int i = 0; i<n; i++) { resetvs(); hascycle = 0; DFS(i, i, -1); if (hascycle == 1) { i--; } } cout << "Case #"<< tc << endl << ans << endl; } return 0; }
Leave a Comment