您的位置:首页 > 其它

wikioi 1069 关押罪犯

2014-01-19 17:04 295 查看

贪心+快排+并查集+图论

做这道题记住一句话:敌人的敌人就是朋友

#include <cstdio>

#include <cstdlib>

const int maxn = 20000;

const int maxm = 200000;

int tail[maxm+1],c[maxm+1],head[maxm+1];

int oppo[maxn+2],fri[maxn+2];

int n, m;

int getfriend(int a)

{

if(fri[a]==a)

return a;

else

fri[a]=getfriend(fri[a]);

return fri[a];

}

void befriend(int a,int b)

{

fri[getfriend(b)]=getfriend(a);

}

int getint()

{

int a;

scanf("%d",&a);

return a;

}

void addedge(int u,int v,int e,int k)

{

tail[e] = v;

head[e]=u;

c[e] = k;

}

void swap(int *a,int *b)

{

int tmp=*a;

*a=*b;

*b=tmp;

}

void sort(int l,int r)

{

int key=c[rand()%(r-l+1)+l];

int i=l,j=r;

while (i<=j)

{

while(c[i]>key)

i++;

while(c[j]<key)

j--;

if(i<=j)

{

swap(&c[i],&c[j]);

swap(&tail[i],&tail[j]);

swap(&head[i],&head[j]);

i++;

j--;

}

}

if(l<j)

sort(l,j);

if(i<r)

sort(i,r);

}

int main()

{

srand(909978797);

n=getint();

m=getint();

for(int i=1;i<=n;i++)

fri[i]=i;

for(int e=1;e<=m;e++)

{

int u=getint();

int v=getint();

int c=getint();

addedge(u,v,e,c);

addedge(v,u,e+m,c);

}

sort(1,m);

bool fight=false;

int num=0;

for(int i=1;i<=m;i++)

{

if(getfriend(head[i])==getfriend(tail[i]))

{

fight=true;

num=i;

break;

}

if(oppo[head[i]]==0)

{

oppo[head[i]]=tail[i];

}

if(oppo[tail[i]]==0)

{

oppo[tail[i]]=head[i];

}

if(oppo[head[i]])

{

befriend(tail[i],oppo[head[i]]);

}

if(oppo[tail[i]])

{

befriend(head[i],oppo[tail[i]]);

}

}

if(fight)

printf("%d",c[num]);

else

printf("0");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: