Fiber Communications
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 4237 | Accepted: 1277 |
Description
Farmer John wants to connect his N (1 <= N <= 1,000) barns (numbered 1..N) with a new fiber-optic network. However, the barns are located in a circle around the edge of a large pond, so he can only connect pairs of adjacent barns. The circular configuration means that barn N is adjacent to barn 1.
FJ doesn't need to connect all the barns, though, since only certain pairs of cows wish to communicate with each other. He wants to construct as few
connections as possible while still enabling all of these pairs to communicate through the network. Given the list of barns that wish to communicate with each other, determine the minimum number of lines that must be laid. To communicate from barn 1 to barn 3, lines must be laid from barn 1 to barn 2 and also from barn 2 to barn 3(or just from barn 3 to 1,if n=3).
FJ doesn't need to connect all the barns, though, since only certain pairs of cows wish to communicate with each other. He wants to construct as few
connections as possible while still enabling all of these pairs to communicate through the network. Given the list of barns that wish to communicate with each other, determine the minimum number of lines that must be laid. To communicate from barn 1 to barn 3, lines must be laid from barn 1 to barn 2 and also from barn 2 to barn 3(or just from barn 3 to 1,if n=3).
Input
* Line 1: Two integers, N and P (the number of communication pairs, 1 <= P <= 10,000)
* Lines 2..P+1: two integers describing a pair of barns between which communication is desired. No pair is duplicated in the list.
* Lines 2..P+1: two integers describing a pair of barns between which communication is desired. No pair is duplicated in the list.
Output
One line with a single integer which is the minimum number of direct connections FJ needs to make.
Sample Input
5 2 1 3 4 5
Sample Output
3
Hint
[Which connect barn pairs 1-2, 2-3, and 4-5.]
Source
啦,被坑了好长时间。。
题目大意:给定一个环和一些点对,点对只能相邻的相连,求满足这些点对连通的最小代价是多少?
额。。一开始还以为是区间统计。。结果自己试了一组样例不太对
5 2
1 4
1 5
分析:我们自然是要考虑瞬时针连接还是逆时针连接咯。
但是这样又变得很麻烦。。
如果只有1~n的线段而不是环是不是很好统计呢?
如果我们要拆除一条线段,那它两个端点逆时针方向必须全部连接。
我们就要找到这端点呢。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 10010
using namespace std;
int n,p,ans;
int vis[1010];
int main(){
freopen("S.in","r",stdin);
freopen("S1.out","w",stdout);
scanf("%d%d",&n,&p);
int u,v;
for(int i=1;i<=p;i++){
scanf("%d%d",&u,&v);
if(u>v)swap(u,v);
vis[u]=1;vis[v]=-1;
}
int Q=0;
for(int i=1;i<=n;i++){Q+=vis[i];if(Q)ans++;}
Q=0;
for(int i=1;i<=n;i++){
Q+=vis[i];if(!Q)continue;
int tmp2=i,cnt2=0;
while(!vis[tmp2]||tmp2==i){cnt2++;tmp2++;if(tmp2==n+1)tmp2=1;}
ans=min(ans,n-cnt2);
}
printf("%d",ans);
return 0;
}