20pts 求助
查看原帖
20pts 求助
711859
ztksc07楼主2024/8/17 19:31

二分答案+二分图染色

AC on #1 #5

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=2e4+10;
const int maxm=1e5+10;
struct Node{
	int to,nxt,w;
}e[2*maxm];
int n,m;
int d[maxm],c[maxn],mid;
int h[maxn],tot;
bool vis[maxn];
void Add(int u,int v,int w){
	tot++;
	e[tot].to=v;
	e[tot].nxt=h[u];
	e[tot].w=w;
	h[u]=tot;
} 
bool dfs(int root,int col){
	vis[root]=1;
	c[root]=col;
	for(int i=h[root];i;i=e[i].nxt){
		int v=e[i].to;
		if(e[i].w<=d[mid]) continue;
		if(vis[v]){
			if(c[root]!=c[v]) continue;
			else return 0;
		} 
		dfs(v,col^1);
	}
	return 1;
}
bool check(){
	memset(vis,0,sizeof(vis));
	memset(c,0,sizeof(c));
	for(int i=1;i<=n;i++){
		if(!vis[i]){
			if(!dfs(i,0)) return 0;
		}
	}
	return 1;
}
int bfind(){
	int l=0,r=m;
	while(l<r){
		mid=(l+r)/2;
		if(check()) r=mid;
		else l=mid+1;
	}
	return l;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		d[i]=w;
		Add(u,v,w);
		Add(v,u,w);
	}
	if(m==1){
		cout<<0;
		return 0;
	} 
	sort(d+1,d+1+m);
	cout<<d[bfind()];
	return 0; 
}

2024/8/17 19:31
加载中...