codevs 1955 光纤通信 USACO

1955 光纤通信

 

USACO

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
 
 
题目描述 Description

农民John 想要用光纤连通他的N (1 <= N <= 1,000)个牲口棚(编号1..N)。但是,牲口棚位于一个大池塘边,他仅可以连通相邻的牲口棚。John不需要连通所有的牲口棚, 因为只有某些奶牛之间想要彼此通讯。在保证这些奶牛通讯的情况下,他想使用最少的光纤完成通信网构件工作。给出想要通讯的成对奶牛的清单,要求求出最少需使用多少根光纤。

输入描述 Input Description

第1行: 2个整数, n 和 p (想要通讯的奶牛对数, 1<=p<=10,000)

第2..p+1行: 2个整数,描述想要通讯的两只奶牛的编号

 

输出描述 Output Description

仅1行,即最少使用光纤数。

样例输入 Sample Input

5 2

1 3

4 5

样例输出 Sample Output

3

数据范围及提示 Data Size & Hint

样例方案:连接1-2,连接2-3, 连接4-5

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 1010
using namespace std;
int n,m,a[maxn*2][maxn*2],b[maxn*2],ans=0x7fffffff;
int main()
{
    int i,j,k;
    scanf("%d%d",&n,&m);
    for(i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        if(x>y)swap(x,y);
        a[x][y]=1;
        a[y][x+n]=1;
        a[x+n][y+n]=1;
    }
    for(i=1;i<=n;i++)//枚举断点 
    {
        memset(b,0,sizeof(b));
        int tot=0;//以i做断点需要连几条边 
        for(j=i;j<=i+n-1;j++)//枚举区间内的点 
        {
            for(k=i+n-1;k>=j;k--)//从大到小枚举找j要连线的最远的点 
            if(a[j][k])
            {
                for(int l=j;l<=k-1;l++)//看l和l+1是否连线,没连则连上tot++ 
                if(b[l]==0)
                {
                    b[l]=1;
                    tot++;
                }
                break;//找到最远的 更小的就不用找了 
            }
        }
        ans=min(ans,tot);
    }
    printf("%d\n",ans);
    return 0;
}

 

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 1010
using namespace std;
int n,m,a[maxn*2][maxn*2],b[maxn*2],to[maxn*2][maxn*2],ans=0x7fffffff;
int max(int a,int b)
{
    return a >= b ? a : b; 
}
int min(int a,int b)
{
    return a <= b ? a : b; 
}
int main()
{
    int i,j,k;
    scanf("%d%d",&n,&m);
    for(i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        if(x>y)swap(x,y);
        
        a[x][y]=1;
        for(j=max(1,y-n+1);j<=x;j++)
          to[j][x]=max(to[j][x],y);
        
        a[y][x+n]=1;
        for(j=max(1,x+1);j<=y;j++)
          to[j][y]=max(to[j][y],x+n);
        
        a[x+n][y+n]=1;
        for(j=max(1,y+1);j<=x+n;j++)
          to[j][x+n]=max(to[j][x+n],y+n);
        
    }
    for(i=1;i<=n;i++)//枚举断点 
    {
        int tot=0,end=0;
        for(j=i;j<=n+i-1;j++)
        {
            if(!to[i][j])continue;
            if(j>end)
            {
                tot+=to[i][j]-j;
                end=to[i][j];
            }
            else
            if(to[i][j]>end)
            {
                tot+=to[i][j]-end;
                end=to[i][j];
            }
        }
        ans=min(ans,tot);
    }
    printf("%d\n",ans);
    return 0;
}

 

 

 

 

posted @ 2016-08-11 17:07  岂是蓬蒿人  阅读(248)  评论(0编辑  收藏  举报