#include <iostream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <string>
typedef unsigned long long ull;
using namespace std;
int m,w,s=1,t,mf,f;
vector<vector<int> > res;
vector<int> p;
void augment(int u,int flow){
if(u==s){
f=flow;
return;
}
if(p[u]==-1)
return;
augment(p[u],min(flow,res[p[u]][u]));
res[p[u]][u]-=f;
res[u][p[u]]+=f;
}
int main(){
while(1){
cin>>m>>w;
if(m==0&&w==0)
return 0;
mf=0;
res.assign(2*m+1,vector<int>(2*m+1));
for(int i=0;i<m-2;i++){
int x,c;
cin>>x>>c;
res[2*x-1][2*x]=res[2*x][2*x-1]=c;
}
for(int i=0;i<w;i++){
int x,y,c;
cin>>x>>y>>c;
res[2*x][2*y-1]=res[2*y][2*x-1]=c;
}
t=2*m;
res[1][2]=res[t-1][t]=res[2][1]=res[t][t-1]=2e9;
while(1){
f=0;
p.assign(2*m+1,-1);
p[s]=s;
queue<int> q;
q.push(s);
while(!q.empty()){
int u=q.front();
q.pop();
if(u==t)
break;
for(int i=1;i<=t;i++){
if(res[u][i]>0&&p[i]==-1)
q.push(i),p[i]=u;
}
}
augment(t,2e9);
if(!f)
break;
mf+=f;
}
cout<<mf<<endl;
}
}
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <string>
typedef unsigned long long ull;
using namespace std;
int m,w,s=1,t,mf,f;
vector<vector<int> > res;
vector<int> p;
void augment(int u,int flow){
if(u==s){
f=flow;
return;
}
if(p[u]==-1)
return;
augment(p[u],min(flow,res[p[u]][u]));
res[p[u]][u]-=f;
res[u][p[u]]+=f;
}
int main(){
while(1){
cin>>m>>w;
if(m==0&&w==0)
return 0;
mf=0;
res.assign(2*m+1,vector<int>(2*m+1));
for(int i=0;i<m-2;i++){
int x,c;
cin>>x>>c;
res[2*x-1][2*x]=res[2*x][2*x-1]=c;
}
for(int i=0;i<w;i++){
int x,y,c;
cin>>x>>y>>c;
res[2*x][2*y-1]=res[2*y][2*x-1]=c;
}
t=2*m;
res[1][2]=res[t-1][t]=res[2][1]=res[t][t-1]=2e9;
while(1){
f=0;
p.assign(2*m+1,-1);
p[s]=s;
queue<int> q;
q.push(s);
while(!q.empty()){
int u=q.front();
q.pop();
if(u==t)
break;
for(int i=1;i<=t;i++){
if(res[u][i]>0&&p[i]==-1)
q.push(i),p[i]=u;
}
}
augment(t,2e9);
if(!f)
break;
mf+=f;
}
cout<<mf<<endl;
}
}
Comments
Post a Comment