CF507E Breaking Good(spfa+dp)

来源:互联网 发布:南音吉他小屋 淘宝 编辑:程序博客网 时间:2024/06/06 20:30

求最短路,同样最短时取好路最多的。还要记录路径。

#include <bits/stdc++.h>using namespace std;#define ll long long#define inf 0x3f3f3f3f#define N 100010inline int read(){    int x=0,f=1;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 x*f;}int n,m,h[N],num=0,dis[N],dp[N],pre[N],res=0;bool inq[N],ans[N];struct edge{    int fr,to,next,op;}data[N<<1];void spfa(){    queue<int>q;memset(inq,0,sizeof(inq));memset(dis,inf,sizeof(dis));    memset(dp,0,sizeof(dp));q.push(1);inq[1]=1;dis[1]=0;dp[1]=0;    while(!q.empty()){        int x=q.front();q.pop();inq[x]=0;        for(int i=h[x];i;i=data[i].next){            int y=data[i].to;            if(dis[y]==dis[x]+1&&dp[x]+data[i].op>dp[y]){                dp[y]=dp[x]+data[i].op;pre[y]=x;                if(!inq[y]) inq[y]=1,q.push(y);            }            if(dis[y]>dis[x]+1){                dis[y]=dis[x]+1;dp[y]=dp[x]+data[i].op;pre[y]=x;                if(!inq[y]) inq[y]=1,q.push(y);            }        }    }}int main(){//  freopen("a.in","r",stdin);    n=read();m=read();    for(int i=1;i<=m;++i){        int x=read(),y=read(),op=read();res+=op;        data[++num].to=y;data[num].next=h[x];h[x]=num;data[num].op=op;data[num].fr=x;        data[++num].to=x;data[num].next=h[y];h[y]=num;data[num].op=op;data[num].fr=y;    }spfa();printf("%d\n",res-dp[n]+dis[n]-dp[n]);int x=n;    while(x!=1){        for(int i=h[x];i;i=data[i].next){            int y=data[i].to;if(y==pre[x]) ans[i+1>>1]=1;        }x=pre[x];    }    for(int i=1;i<=m;++i){        if(ans[i]&&data[i<<1].op==0) printf("%d %d %d\n",data[i<<1].fr,data[i<<1].to,1);        if(!ans[i]&&data[i<<1].op==1) printf("%d %d %d\n",data[i<<1].fr,data[i<<1].to,0);    }return 0;}
原创粉丝点击