题目描述 传送门
尝试删
m
条边重新计算
但对于点
i
只有删除了以
预处理好每个点的最短路树,这样最多计算
O(n2)
次单源最短路,时间复杂度降为
O(n2mlogn)
坑点:要用第二小的边代替删去的边。
代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int INF=1e9;
const int maxn=104,maxm=1005;
int h[maxn],d[maxn],sum[maxn],p[maxn],secedge[maxn][maxn],edgeid[maxn][maxn];
bool vis[maxn],need[maxn][maxm*2];
struct Edge{
int t,d,nxt;
Edge(int a=0,int b=0,int c=0):t(a),d(b),nxt(c){}
}edges[maxm*2];
int n,m,cnt,L;
struct heap{
int d,v;
heap(int a=0,int b=0):d(a),v(b){}
bool operator<(const heap&a)const{
return d>a.d;
}
};
void addedge(int from,int to,int dist){
edges[++cnt]=Edge(to,dist,h[from]);
h[from]=cnt;
edges[++cnt]=Edge(from,dist,h[to]);
h[to]=cnt;
edgeid[from][to]=edgeid[to][from]=cnt;
}
int main(){
while(scanf("%d%d%d",&n,&m,&L)!=EOF){
cnt=-1;
memset(h,-1,sizeof(h));
memset(secedge,0,sizeof(secedge));
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(!secedge[a][b]){
addedge(a,b,c);
secedge[a][b]=secedge[b][a]=INF;
}
else if(c<edges[edgeid[a][b]].d){
secedge[a][b]=secedge[b][a]=edges[edgeid[a][b]].d;
edges[edgeid[a][b]].d=edges[edgeid[a][b]^1].d=c;
}
else if(c<secedge[a][b]) secedge[a][b]=secedge[b][a]=c;
}
memset(sum,0,sizeof(sum));
memset(need,0,sizeof(need));
int c=0;
for(int i=1;i<=n;i++){
memset(vis,0,sizeof(vis));
priority_queue<heap>q;
q.push(heap(0,i));
for(int i=1;i<=n;i++) d[i]=INF;
d[i]=0;
while(!q.empty()){
heap x=q.top();q.pop();
int u=x.v;
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i>-1;i=edges[i].nxt){
int v=edges[i].t;
if(d[u]+edges[i].d<d[v]){
d[v]=d[u]+edges[i].d;
p[v]=i;
q.push(heap(d[v],v));
}
}
}
for(int j=1;j<=n;j++){
sum[i]+=d[j]==INF?L:d[j];
if(j!=i) need[i][p[j]]=need[i][p[j]^1]=1;
}
c+=sum[i];
}
int ans=0;
for(int i=0;i<2*m;i+=2){
int c1=0;
for(int j=1;j<=n;j++){
if(need[j][i]){
swap(secedge[edges[i].t][edges[i^1].t],edges[i].d);
edges[i^1].d=edges[i].d;
memset(vis,0,sizeof(vis));
priority_queue<heap>q;
q.push(heap(0,j));
for(int i=1;i<=n;i++) d[i]=INF;
d[j]=0;
while(!q.empty()){
heap x=q.top();q.pop();
int u=x.v;
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i>-1;i=edges[i].nxt){
int v=edges[i].t;
if(d[u]+edges[i].d<d[v]){
d[v]=d[u]+edges[i].d;
q.push(heap(d[v],v));
}
}
}
for(int k=1;k<=n;k++)
c1+=d[k]==INF?L:d[k];
swap(secedge[edges[i].t][edges[i^1].t],edges[i].d);
edges[i^1].d=edges[i].d;
}
else c1+=sum[j];
}
ans=max(ans,c1);
}
printf("%d %d\n",c,ans);
}
return 0;
}