思路
- 根据不同的关系来建立不同的边
- 1.若X=1,则建立边(u,v,0),表示两者相等.
- 2.若X=2,则建立边(u,v,1),表示v比u大一.
- 3.若X=3,则建立边(v,u,0),表示u大于等于v.
- 4.若X=4,则建立边(v,u,1),表示u比v大一.
- 5.若X=5,则建立边(u,v,0),表示u小于等于v.
- 再用一个超级原点,和所有的点连一条从超级原点到所有边的权值为1的边,这样就能保证所有点的值都大于0
- 然后跑一遍spfa,求出单源最长路即可,这里spfa里要用stack或者手写队列,否则直接用STL里的queue会T
代码
#include <stack>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+5;
const int M=3e5+5;
int n,k;
int h[N];int e[M];int ne[M];int w[M];int idx;
ll dist[N];
int cnt[N];
bool st[N];
stack<int> q;
void add(int a,int b,int c){
e[idx]=b,w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}
bool SPFA(){
memset(dist, -0x3f, sizeof dist);
dist[0] = 0;
q.push(0);
st[0] = true;
while (!q.empty())
{
int t = q.top();
st[t] = false;
q.pop();
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] < dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n + 1) return false;
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return true;
}
int main(){
memset(h,-1,sizeof h);
scanf("%d%d",&n,&k);
while(k--){
int x;
scanf("%d",&x);
int a,b;
scanf("%d%d",&a,&b);
if(x==1){
add(a,b,0);
add(b,a,0);
}
if(x==2){
add(a,b,1);
}
if(x==3){
add(b,a,0);
}
if(x==4){
add(b,a,1);
}
if(x==5){
add(a,b,0);
}
}
for(int i=1;i<=n;i++){
add(0,i,1);
}
if(!SPFA()){
cout << -1;
}else{
ll res=0;
for(int i=1;i<=n;i++)res+=dist[i];
cout << res;
}
}