bzoj 4773: 負環——倍增
阿新 • • 發佈:2017-10-02
mat des == 負數 typedef void return 忘記 esc
1 2 -2
2 1 1
2 3 -10
3 2 10
3 1 -10
1 3 10
Description
在忘記考慮負環之後,黎瑟的算法又出錯了。對於邊帶權的有向圖 G = (V, E),請找出一個點數最小的環,使得 環上的邊權和為負數。保證圖中不包含重邊和自環。Input
第1兩個整數n, m,表示圖的點數和邊數。 接下來的m行,每<=三個整數ui, vi, wi,表<=有一條從ui到vi,權值為wi的有向邊。 2 <= n <= 300 0 <= m <= n(n <= 1) 1 <= ui, vi <= n |wi| <= 10^4Output
僅一行一個整數,表示點數最小的環上的點數,若圖中不存在負環輸出0。Sample Input
3 61 2 -2
2 1 1
2 3 -10
3 2 10
3 1 -10
1 3 10
Sample Output
2 ————————————————————————— f[i][j][k]=mins(f[i-1][a][c]+f[1][c][b]) 轉移過來 但是這樣其實有點慢 我們可以跑一波倍增來確定答案#include<cstdio> #include<cstring> #include<algorithm> #include<vector> using std::min; const int M=357View Code; int read(){ int ans=0,f=1,c=getchar(); while(c<‘0‘||c>‘9‘){if(c==‘-‘) f=-1; c=getchar();} while(c>=‘0‘&&c<=‘9‘){ans=ans*10+(c-‘0‘); c=getchar();} return ans*f; } typedef int mat[M][M]; mat f[15],ly,now; int n,m,ans; bool pd(mat s){ for(int i=1;i<=n;i++)if(s[i][i]<0) return 1; return 0; } void mins(int &x,int y){if(x>y) x=y;} int main(){ int x,y,w; n=read(); m=read(); memset(f,0x3f,sizeof(f)); for(int i=1;i<=n;i++) f[0][i][i]=0; for(int i=1;i<=m;i++) x=read(),y=read(),w=read(),mins(f[0][x][y],w); for(int i=1;i<=8;i++){ for(int a=1;a<=n;a++) for(int c=1;c<=n;c++) for(int b=1;b<=n;b++) mins(f[i][a][b],f[i-1][a][c]+f[i-1][c][b]); } if(!pd(f[8])) return puts("0"),0; memset(ly,0x3f,sizeof(mat)); for(int i=1;i<=n;i++) ly[i][i]=0; for(int i=8;i>=0;i--){ memset(now,0x3f,sizeof(mat)); for(int a=1;a<=n;++a) for(int c=1;c<=n;++c) for(int b=1;b<=n;++b) mins(now[a][b],f[i][a][c]+ly[c][b]); if(!pd(now)){ ans|=1<<i; memcpy(ly,now,sizeof(mat)); } } printf("%d",ans+1); return 0; }
bzoj 4773: 負環——倍增