将每个点分成两个点,然后再来建立相应的有向边,转换为最小完美匹配问题,按照最小费用最大流问题来求解即可,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
class Edge{
public:
int from, to, cap, flow, cost;
Edge(int fr, int t, int ca, int fl, int c):from(fr),to(t),cap(ca),flow(fl),cost(c){}
};
class Solve{
public:
int n;
vector<Edge> edge;
vector<int> G[210];
const int Inf = 0x3f3f3f3f;
void addEgde(int from,int to,int cap,int flow,int cost){
edge.push_back(Edge(from,to,cap,flow,cost));
edge.push_back(Edge(to,from,0,0,-cost));
int m = edge.size();
G[from].push_back(m-2);
G[to].push_back(m - 1);
}
void Init(){
edge.clear();
for (int i = 0; i < 210; i++) G[i].clear();
for (int i = 1; i <= n; i++){
addEgde(0,i,1,0,0);
addEgde(n + i, 2 * n + 1, 1, 0, 0);
}
for (int i = 1; i <= n; i++){
while (true){
int a, b;
cin >> a;
if (a == 0) break;
cin >> b;
addEgde(i, a + n, 1, 0, b);
}
}
}
bool BellmanFloyd(int start,int end,int &flow,int &cost){
int price[210];
memset(price, Inf, sizeof(price));
price[start] = 0;
int parent[210];
int Flow[210],inq[210];
Flow[start] = Inf;
memset(inq, 0, sizeof(inq));
queue<int> q;
q.push(start);
inq[start] = 1;
while (!q.empty()){
int id = q.front();
q.pop();
inq[id] = 0;
for (int i = 0; i < G[id].size(); i++){
int ide = G[id][i];
int to = edge[ide].to;
if (edge[ide].cap > edge[ide].flow&&price[to] > price[id] + edge[ide].cost){
Flow[to] = min(Flow[id], edge[ide].cap - edge[ide].flow);
price[to] = price[id] + edge[ide].cost;
parent[to] = ide;
if (!inq[to]){
q.push(to);
inq[to] = 1;
}
}
}
}
if (price[end] == Inf) return false;
flow += Flow[end];
cost += price[end] * Flow[end];
for (int i = end; i != start; i = edge[parent[i]].from){
edge[parent[i]].flow += Flow[end];
edge[parent[i] ^ 1].flow -= Flow[end];
}
return true;
}
void MaxFlow(int start,int end){
int flow = 0, cost = 0;
while (BellmanFloyd(start, end, flow, cost));
if (flow < n) cout << "N" << endl;
else cout << cost << endl;
}
void Deal(){
Init();
MaxFlow(0, 2 * n + 1);
}
};
int main(){
Solve a;
while (cin >> a.n){
if (a.n == 0) break;
a.Deal();
}
return 0;
}