題意就是讓你求兩次1到n的最短路。這題應該可以用最短路來求解吧,只需要將第一次用到的邊刪去即可。我這裡是按照算法競賽入門經典裡面提到拆點+最小費最大流。
#include
using namespace std;
const int N=1024*4;
const int inf=1<<24;
struct Edge
{
int from,to,cap,flow,cost;
};
vectoredges;
vectorG[N];
int n,m;
int inq[N],p[N],d[N],a[N];
void AddEdge(int from, int to,int cap, int cost)
{
Edge tp;
tp.from=from,tp.to=to,tp.cap=cap,tp.flow=0,tp.cost=cost;
edges.push_back(tp);
tp.from=to,tp.to=from,tp.cap=0,tp.flow=0,tp.cost=-cost;
edges.push_back(tp);
int g=edges.size();
G[from].push_back(g-2);
G[to].push_back(g-1);
}
int BellmanFord(int s,int t,int &flow, int &cost)
{
int i,j,u;
for(i=0; iQ;
Q.push(s);
while(!Q.empty())
{
u=Q.front();
Q.pop();
inq[u]=0;
for(i=0; ie.flow&&d[e.to]>d[u]+e.cost)
{
d[e.to]=d[u]+e.cost;
p[e.to]=G[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if(!inq[e.to])
{
Q.push(e.to);
inq[e.to]=1;
}
}
}
}
if(d[t]==inf ) return 0;
flow+=a[t];
cost+=d[t]*a[t];
u=t;
while(u!=s)
{
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return 1;
}
int Mincost(int s,int t)
{
int flow=0,cost=0;
BellmanFord(s,t,flow,cost);
return cost;
}
int main()
{
int i,u,v,c;
while(~scanf(%d%d,&n,&m))
{
for(i=0; i