您的位置:首页 > 其它

pku 1944 Fiber Communications(枚举+贪心)

2009-12-04 22:52 232 查看
[code]如果去掉最后一个顶点可以和第一个顶点相连这个条件,那么该怎么解?

O(P)的贪心就可以了。

因为答案必定是无环的,那么枚举断点,然后采用贪心,就可以得到O(np)的解法。

#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <algorithm>
#include <iostream>
#define PI 3.14159265358979323846264338327950288
#define _clr(a,b) memset(a,b,sizeof(a))
template<class T> T _abs(T a)
{ if(a<0) return -a;return a;}
template<class T> void get_min(T& a,T b)
{ if(a>b) a=b;}
template<class T> void get_max(T& a,T b)
{ if(a<b) a=b;}
using namespace std;
struct node
{
int start,end;
}nodes[30005];
bool operator<(node &a,node &b)
{
return a.start<b.start;
}
int N,P;
int solve(int p,int q,int &nodeStart)
{
int right=-1,sum=0,pnode=nodeStart;
while(nodes[pnode].start<p) pnode++;
nodeStart=pnode;
while(1)
{
if(nodes[pnode].start>=q||pnode>=3*P) break;
if(nodes[pnode].end<q&&nodes[pnode].start>=p)
{
if(nodes[pnode].end>right)
{
if(nodes[pnode].start<=right) sum+=nodes[pnode].end-right;
else sum+=nodes[pnode].end-nodes[pnode].start;
right=nodes[pnode].end;
}
}
pnode++;
}
return sum;
}
int main()
{
scanf("%d%d",&N,&P);
int start,end,ans=INT_MAX,p=0;
for(int i=0;i<P;i++)
{
scanf("%d%d",&start,&end);
if(start>end) swap(start,end);
nodes[i].start=start;
nodes[i].end=end;
nodes[i+P].start=end;
nodes[i+P].end=start+N;
nodes[i+2*P].start=start+N;
nodes[i+2*P].end=end+N;
}
sort(nodes,nodes+3*P);
for(int i=1;i<=N;i++)
{
ans=min(ans,solve(i,i+N,p));
}
printf("%d/n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: