传送门
我菜到没有看出这是一道费用流的板子题;
每个点只能走一次,可以想到拆点的思想;
对于除了S和T的点,拆点的连边容量为1,费用为0;
其他的边的容量定为1,费用为路径长度,跑出最大流即为最大天数,最小费用和为最短路径;
#include
#include
#include
#include
#include
using namespace std;
const int maxn=100001;
const int inf=1e9;
int n,m,s,t,maxflow,mincost;
struct Edge{
int next,to,dis,flow;
}edge[maxn<<1];
int num_edge=-1,head[maxn],pre[maxn],dis[maxn],flow[maxn],last[maxn];
void add_edge(int from,int to,int flow,int dis)
{
edge[++num_edge].next=head[from];
edge[num_edge].dis=dis;
edge[num_edge].flow=flow;
edge[num_edge].to=to;
head[from]=num_edge;
}
void add(int x,int y,int z,int f) {add_edge(x,y,z,f); add_edge(y,x,0,-f);}
bool vis[maxn];
queue <int> q;
bool spfa(int s,int t)
{
memset(dis,0x7f,sizeof(dis));
memset(flow,0x7f,sizeof(flow));
memset(vis,0,sizeof(vis));
q.push(s); vis[s]=1; pre[t]=-1; dis[s]=0;
while (!q.empty())
{
int now=q.front(); q.pop();
vis[now]=0;
for (int i=head[now]; i!=-1; i=edge[i].next)
{
if (edge[i].flow>0 && dis[edge[i].to]>dis[now]+edge[i].dis)//正边
{
dis[edge[i].to]=dis[now]+edge[i].dis;
flow[edge[i].to]=min(flow[now],edge[i].flow);
pre[edge[i].to]=now;
last[edge[i].to]=i;
if (!vis[edge[i].to])
{
vis[edge[i].to]=1;
q.push(edge[i].to);
}
}
}
}
return pre[t]!=-1;
}
void MCMF(int s,int t)
{
while (spfa(s,t))
{
int now=t;
maxflow+=flow[t];
mincost+=flow[t]*dis[t];
while (now!=s)
{
edge[last[now]].flow-=flow[t];
edge[last[now]^1].flow+=flow[t];
now=pre[now];
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
int S=1,T=n;
for (int i=2; i<=n-1; i++) add(i,i+n,1,0);
for (int i=1; i<=m; i++)
{
int x,y,z; scanf("%d%d%d",&x,&y,&z);
if (x==1) add(S,y,1,z);
else if (y==n) add(x+n,T,1,z);
else add(x+n,y,1,z);
}
// for (int i=0; i<=num_edge; i++) printf("%d: %d %d %d %d\n",i,edge[i^1].to,edge[i].to,edge[i].flow,edge[i].dis);
MCMF(S,T);
printf("%d %d",maxflow,mincost);
return 0;
}