spoj segment

差分约束  离散化端点之后把端点和相邻端点之间的线段当作新图的顶点

提供一组样例,wa的估计都wa这了

input

5
1 2 1
1 3 0
2 4 0
3 5 0
4 5 0

output

1

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define N 410
using namespace std;
int num[N*4];
int tim[N*4],dis[N*4];
bool vis[N*4];
int head[N*4],cnt,nn,nnn;
struct Edge{
    int v,w,next;
}edge[N*7];
void init(){
    memset(head,-1,sizeof(head));
    cnt=0;
}
void addedge(int u,int v,int w){
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}
bool spfa(){
    int i;
    queue<int>q;
    for(i=1;i<nnn;i++)dis[i]=80000000;
    dis[0]=0;
    memset(vis,0,sizeof(vis));
    memset(tim,0,sizeof(tim));
    q.push(0);
    vis[0]=1,tim[0]=1;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        vis[u]=0;
        if(tim[u]>=nnn)return 0;
        for(int i=head[u];i!=-1;i=edge[i].next){
            int v=edge[i].v;
            if(dis[v]>dis[u]+edge[i].w){
                dis[v]=dis[u]+edge[i].w;
                if(vis[v]==0){
                    vis[v]=1;
                    tim[v]++;
                    q.push(v);
                }
            }
        }
    }
    return 1;
}
int main(){
    int i,a[N],b[N],c[N],k,n;
    //freopen("a.txt","r",stdin);
    //freopen("b1.txt","w",stdout);
    scanf("%d",&n);{
        k=0;
        for(i=1;i<=n;i++){
            scanf("%d %d %d",&a[i],&b[i],&c[i]);
            //num[k++]=(ll)a[i]*2;
            //num[k++]=(ll)b[i]*2-1;
            num[k++]=a[i];
            num[k++]=b[i];
        }
        sort(num,num+k);
        nn=unique(num,num+k)-num;
        nnn=nn*2;
        for(i=1;i<=n;i++){
            //a[i]=lower_bound(num,num+nn,(ll)a[i]*2)-num;
            //b[i]=lower_bound(num,num+nn,(ll)b[i]*2-1)-num;
            a[i]=(lower_bound(num,num+nn,a[i])-num)*2;
            b[i]=(lower_bound(num,num+nn,b[i])-num)*2-1;
        }
        int l=1,h=n,ans=1000;
        while(l<=h){
            int mid=(l+h)>>1;
            init();
            for(i=1;i<=n;i++){
                addedge(a[i],b[i],mid);
                addedge(b[i],a[i],-1);
            }
            for(i=1;i<nnn;i++)
                addedge(i,i-1,0);
            if(spfa()){
                h=mid-1;
                ans=min(mid,ans);
            }
            else
                l=mid+1;
        }
        printf("%d\n",ans);
    }
    return 0;
}



你可能感兴趣的:(c,input,output)