Ultraviolet A 2038-Strategic game (minimum vertex overwrite or tree DP in a bipartite graph)
Strategic game
Description
Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. now he has the following problem. he must defend a medieval city, the roads of which form a tree. he has to put the minimum number of soldiers on the nodes so that they can observe all the edges. can you help him?
Your program shocould find the minimum number of soldiers that Bob has to put for a given tree.
For example for the tree:
The solution is one soldier (at the node 1 ).
Input
The input file contains several data sets in text format. Each data set represents a tree with the following description:
The number of nodes the description of each node in the following format:
Node_identifier :( number_of_roads) node_identifier1 node_identifier2? Node_identifiernumber_of_roads
Or
Node_identifier :( 0)
The node identifiers are integer numbers
0And
N-1,
NNodes (
0 <n ≤ 1500). Every edge appears only once in the input data.
Output
The output shoshould be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers ).
Sample Input40:(1) 11:(2) 2 32:(0)3:(0)53:(3) 1 4 21:(1) 02:(0)0:(0)4:(0)
If a tree is given, select as few points as possible, so that each unselected node is at least adjacent to a selected node. The minimum number of nodes to be selected.
Idea: The minimum vertex overwrite of the classic binary graph is also the classic tree-like DP.
Minimum vertex overwrite = maximum matching (bidirectional graph)/2
The data is large, and an adjacent table is used. Otherwise it will time out.
#include #include #include #include #include #include #include #include #include #include #includeusing namespace std;const int MAXN = 1510;int nx, ny;int used[MAXN];int cx[MAXN], cy[MAXN];vectorg[MAXN];int Find(int u){ for(int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if(!used[v]) { used[v] = 1; if(cy[v]==-1 || Find(cy[v])) { cy[v] = u; cx[u] = v; return 1; } } } return 0;}int Hungary(){ int res = 0; memset(cx, -1, sizeof(cx)); memset(cy, -1, sizeof(cy)); for(int i = 0; i < nx; i++) { if(cx[i] == -1) { memset(used, 0, sizeof(used)); if(Find(i)) res++; } } return res;}int main(){ //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int t, n, num; int x, y; while(cin>>n) { if(!n) break; ny = nx = n; t = n; for(int i = 0; i < n; i++) g[i].clear(); while(t--) { scanf("%d:(%d)", &x, &num); while(num--) { scanf("%d", &y); g[x].push_back(y); g[y].push_back(x); } } printf("%d\n", Hungary()/2); } return 0;}