Description
There are two machines A and B. Machine A has n kinds of working modes, which is called mode_0, mode_1, ..., mode_n-1, likewise machine B has m kinds of working modes, mode_0, mode_1, ... , mode_m-1. At the beginning they are both work at mode_0.
For k jobs given, each of them can be processed in either one of the two machines in particular mode. For example, job 0 can either be processed in machine A at mode_3 or in machine B at mode_4, job 1 can either be processed in machine A at mode_2 or in machine B at mode_4, and so on. Thus, for job i, the constraint can be represent as a triple (i, x, y), which means it can be processed either in machine A at mode_x, or in machine B at mode_y.
Obviously, to accomplish all the jobs, we need to change the machine's working mode from time to time, but unfortunately, the machine's working mode can only be changed by restarting it manually. By changing the sequence of the jobs and assigning each job to a suitable machine, please write a program to minimize the times of restarting machines.
Input
The input will be terminated by a line containing a single zero.
Output
Sample Input
5 5 10 0 1 1 1 1 2 2 1 3 3 1 4 4 2 1 5 2 2 6 2 3 7 2 4 8 3 3 9 4 3 0
Sample Output
3
二分图的最小顶点覆盖数=最大匹配数
每个任务建立一条边,最小点覆盖就是求最少的点可以连接到所有的边。本题就是最小点覆盖=最大二分匹配数。
注意一点就是:题目说初始状态为0,所以如果一个任务有一点为0的边不要添加。因为不需要代价
匈牙利算法
#include <iostream> #include <string.h> using namespace std; int n,m,k; int map[101][101],vis[101],pre[101]; bool DFS(int x) { for(int i=0;i<m;i++) { if(!vis[i]&&map[x][i]) { vis[i]=1; if(!pre[i]||DFS(pre[i])) { pre[i]=x; return true; } } } return false; } int main() { while(cin>>n&&n!=0) { int i,j,ans=0; memset(pre,0,sizeof(pre)); memset(map,0,sizeof(map)); cin>>m>>k; for(i=1;i<=k;i++) { int j,a,b; cin>>j>>a>>b; if(a>0&&b>0) map[a][b]=1; } for(i=0;i<n;i++) { memset(vis,0,sizeof(vis)); if(DFS(i)) ans++; } cout<<ans<<endl; } return 0; }