传送门
题意:
思路: 一开始被题意迷惑了,没看出来差分约束,老菜鸡啦。首先看到aj=ai+1a_j=a_i+1aj=ai+1可以把aia_iai分成奇偶,让后这个图就变成一个二分图了。再考虑如何连边:
(1) 对于b=1b=1b=1的情况,aj=ai+1a_j=a_i+1aj=ai+1,转化成不等式就是ai<=aj−1a_i<=a_j-1ai<=aj−1和aj<=ai+1a_j<=a_i+1aj<=ai+1,所以建图方式为(j,i,−1)(j,i,-1)(j,i,−1)和(i,j,1)(i,j,1)(i,j,1)。
(2) 对于b=0b=0b=0的情况,∣ai−aj∣=1|a_i-a_j|=1∣ai−aj∣=1,去掉不等式又可以分成两种情况:
①①① aj=ai+1a_j=a_i+1aj=ai+1 连边方式跟上面一样
②②② ai=aj+1a_i=a_j+1ai=aj+1,转化成不等式ai<=aj+1a_i<=a_j+1ai<=aj+1和aj<=ai−1a_j<=a_i-1aj<=ai−1,连边为(j,i,1)(j,i,1)(j,i,1)和(i,j,−1)(i,j,-1)(i,j,−1)。
可以发现第二种情况有四条边,即(i,j,1),(i,j,−1),(j,i,1),(j,i,−1)(i,j,1) ,(i,j,-1),(j,i,1),(j,i,-1)(i,j,1),(i,j,−1),(j,i,1),(j,i,−1)。但是对于(i,j,1)(i,j,1)(i,j,1)转化成不等式j−i<=1j-i<=1j−i<=1,把(i,j,−1)(i,j,-1)(i,j,−1)转成不等式j−i<=−1j-i<=-1j−i<=−1,当第一个成立的时候,第二个显然成立,所以只保留第一个就行啦。
让后跑差分约束就好啦,nnn比较小,直接floydfloydfloyd跑顺便判断一下负环就好啦。
这里用并查集判断的二分图。
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;const int N=310,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;int n,m;
int g[N][N],p[N*2];int find(int x) { return x==p[x]? x:p[x]=find(p[x]); }bool check()
{for(int i=1;i<=n;i++) if(find(i)==find(i+n)) return true;return false;
}bool floyd()
{for(int k=1;k<=n;k++)for(int i=1;i<=n;i++){for(int j=1;j<=n;j++)g[i][j]=min(g[i][j],g[i][k]+g[k][j]);if(g[i][i]<0) return true;}return false;
}int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);scanf("%d%d",&n,&m);for(int i=1;i<=n*2;i++) p[i]=i;memset(g,0x3f,sizeof(g));for(int i=1;i<=n;i++) g[i][i]=0;for(int i=1;i<=m;i++){int a,b,op; scanf("%d%d%d",&a,&b,&op);g[a][b]=1; g[b][a]=-1;if(!op) g[b][a]=1;p[find(a)]=find(b+n);p[find(a+n)]=find(b);}if(check()||floyd()) { puts("NO"); return 0; }int ans=-1,id=0;for(int i=1;i<=n;i++){for(int j=1;j<=n;j++)if(g[i][j]>ans) ans=g[i][j],id=i;}puts("YES");printf("%d\n",ans);for(int i=1;i<=n;i++) printf("%d ",g[id][i]);return 0;
}
/**/