CF1450E Capitalism
Description
A society can be represented by a connected, undirected graph of $ n $ vertices and $ m $ edges. The vertices represent people, and an edge $ (i,j) $ represents a friendship between people $ i $ and $ j $ .
In society, the $ i $ -th person has an income $ a_i $ . A person $ i $ is envious of person $ j $ if $ a_j=a_i+1 $ . That is if person $ j $ has exactly $ 1 $ more unit of income than person $ i $ .
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as $ \max\limits_{1 \leq i \leq n} a_i - \min\limits_{1 \leq i \leq n} a_i $ .
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Solution
将无向的关系建无向的边,边权为1,有向的关系建双向边,正向边权为1,逆向的边权为-1
每条边的边权就表示终点与起点的差
每一对点的最短路表示的是满足全图限制下的两点最大差
那么答案就是所有点对的最短路最大值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> using namespace std; int n,m,dist[205][205],ans=-1,tag; struct Node { int x,y,b; }node[2005]; inline int read() { int f=1,w=0; char ch=0; while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();} while(ch>='0'&&ch<='9') w=(w<<1)+(w<<3)+ch-'0',ch=getchar(); return f*w; } int main() { n=read(),m=read(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i!=j) dist[i][j]=1e9; else dist[i][j]=0; for(int i=1;i<=m;i++) { node[i]=(Node){read(),read(),read()}; int x=node[i].x,y=node[i].y; if(node[i].b) dist[x][y]=1,dist[y][x]=-1; else dist[x][y]=dist[y][x]=1; } for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) dist[i][j]=min(dist[i][k]+dist[k][j],dist[i][j]); for(int i=1;i<=n;i++) { if(dist[i][i]<0) return puts("NO"),0; for(int j=1;j<=m;j++) if(dist[i][node[j].x]==dist[i][node[j].y]) return puts("NO"),0; for(int j=1;j<=n;j++) if(dist[i][j]>ans) ans=dist[i][j],tag=i; } puts("YES"),printf("%d\n",ans); for(int i=1;i<=n;i++) printf("%d ",dist[tag][i]); return 0; }