典型的最小费用最大流。只要把一个点拆成两个,中间连一条容量1费用0的边来限制每个点只用一次就好。
要注意第1个点和第n个点不用限制次数,以及从1到n的边容量为1。
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int N=410,M=30010,inf=0x7fffffff;
struct edge{
int y,next,f,c;
}data[M*2];
int n,m,s,t,num,h[N],cost[N],pre[N],path[N],fmax[N];
bool vis[N];
queue<int> q;
inline int read(){
int x=0,f=0;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return f?-x:x;
}
inline void add(int x,int y,int f,int c){
data[++num].y=y;data[num].f=f;data[num].c=c;
data[num].next=h[x];h[x]=num;
data[++num].y=x;data[num].f=0;data[num].c=-c;
data[num].next=h[y];h[y]=num;
}
bool spfa(int s,int t){
memset(cost,0x3f,sizeof cost);
memset(vis,false,sizeof vis);
while(!q.empty())q.pop();
q.push(s);cost[s]=0;vis[s]=true;fmax[s]=inf;pre[t]=-1;
while(!q.empty()){
int u=q.front();q.pop();vis[u]=false;
for(int i=h[u];i!=-1;i=data[i].next){
int v=data[i].y;
if(data[i].f>0&&cost[v]>cost[u]+data[i].c){
cost[v]=cost[u]+data[i].c;
pre[v]=u;path[v]=i;
fmax[v]=min(data[i].f,fmax[u]);
if(!vis[v]){vis[v]=true;q.push(v);}
}
}
}
return pre[t]!=-1;
}
void mcmf(int s,int t){
int flow=0,charge=0;
while(spfa(s,t)){
flow+=fmax[t];
charge+=cost[t]*fmax[t];
for(int i=t;i!=s;i=pre[i]){
data[path[i]].f-=fmax[t];
data[path[i]^1].f+=fmax[t];
}
}
printf("%d %d",flow,charge);
}
int main(){
n=read();m=read();s=1;t=2*n;
memset(h,-1,sizeof h);num=-1;
add(1,1+n,inf,0);add(n,n*2,inf,0);
for(int i=2;i<n;i++)add(i,i+n,1,0);
for(int x,y,c,i=1;i<=m;i++){
x=read();y=read();c=read();
if(x==1&&y==n)add(1+n,n,1,c);
else add(x+n,y,inf,c);
}
mcmf(s,t);
return 0;
}