光纤通信(codevs 1955)

题目描述 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<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define N 1010
#define M 10010 
using namespace std;
int a[N*2][N*2],vis[N*2],n,m;
int read()
{
    char c=getchar();int num=0;
    while(c<'0'||c>'9'){c=getchar();}
    while(c>='0'&&c<='9'){num=num*10+c-'0';c=getchar();}
    return num;
}
int main()
{
    n=read();m=read();
    for(int i=1;i<=m;i++)
    {
        int x=read(),y=read();
        if(x>y)swap(x,y);
        a[x][y]=1;
        a[y][x+n]=1;
        a[x+n][y+n]=1;
    }
    int ans=n;
    for(int i=1;i<=n;i++)//枚举将环变成链断点
    {
        memset(vis,0,sizeof(vis));
        int p=0;
        for(int j=i;j<=n+i-1;j++)//枚举内的点 
        {
            for(int k=n+i-1;k>=j;k--)//从后向前找出和j点有关系的点 
              if(a[j][k])
              {
                  for(int l=j;l<k;l++)
                  if(!vis[l])
                  {
                      vis[l]=1;
                      p++;
                  }
                break;//因为是从后向前找的,所以只找一次 
              } 
        }
        ans=min(ans,p);
    }
    printf("%d\n",ans);
    return 0;
}
View Code

 

posted @ 2016-08-11 19:36  karles~  阅读(245)  评论(0编辑  收藏  举报