P2153-[SDOI2009]晨跑

  1 #include<bits/stdc++.h>
  2 #define _for(i,a,b) for(register int i = (a);i < b;i ++)
  3 #define _rep(i,a,b) for(register int i = (a);i > b;i --)
  4 #define INF 0x3f3f3f3f
  5 #define MOD 100000000
  6 #define maxn 100003
  7 #define pb push_back
  8 #define debug() printf("Miku Check OK!\n")
  9 typedef long long ll;
 10 
 11 using namespace std;
 12 typedef pair<int,int> P;
 13 inline ll read()
 14 {
 15     ll ans = 0;
 16     char ch = getchar(), last = ' ';
 17     while(!isdigit(ch)) last = ch, ch = getchar();
 18     while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
 19     if(last == '-') ans = -ans;
 20     return ans;
 21 }
 22 inline void write(ll x)
 23 {
 24     if(x < 0) x = -x, putchar('-');
 25     if(x >= 10) write(x / 10);
 26     putchar(x % 10 + '0');
 27 }
 28 int ver[maxn],Next[maxn],head[maxn],val[maxn],cost[maxn];
 29 //incf[i]为i在此趟BFS流过的流量
 30 int vis[maxn],incf[maxn],pre[maxn];
 31 int n,m,s,t,tot,maxflow,ans;
 32 int d[maxn];
 33 void add(int x,int y,int w,int c)
 34 {
 35     ver[++tot] = y,Next[tot] = head[x],head[x] = tot,val[tot] = w,cost[tot] = c;
 36     ver[++tot] = x,Next[tot] = head[y],head[y] = tot,val[tot] = 0,cost[tot] = -c;
 37 }
 38 bool spfa()
 39 {
 40     memset(vis,0,sizeof(vis));
 41     memset(d,0x3f,sizeof(d));
 42     queue<int> q;
 43     q.push(s);
 44     vis[s] = 1;
 45     d[s] = 0;
 46     incf[s] = INF;
 47     while(!q.empty())
 48     {
 49         int x = q.front();
 50         q.pop();
 51         vis[x] = 0;
 52         for(int i = head[x]; i; i = Next[i])
 53             if(val[i])
 54             {
 55                 int y = ver[i];
 56                 if(d[y] > d[x] + cost[i])
 57                 {
 58                     d[y] = d[x] + cost[i];
 59                     incf[y] = min(incf[x],val[i]);
 60                     pre[y] = i;
 61                     if(!vis[y])
 62                         vis[y] = 1,q.push(y);
 63                 }
 64             }
 65     }
 66     if(d[t]==INF)
 67         return false;
 68     return true;
 69 }
 70 void update()
 71 {
 72     int x = t;
 73     while(x != s)
 74     {
 75         int i = pre[x];
 76         val[i] -= incf[t];
 77         val[i^1] += incf[t];
 78         x = ver[i^1];
 79     }
 80     maxflow += incf[t];
 81     ans += d[t] * incf[t];
 82 }
 83 int main()
 84 {
 85     n = read();
 86     m = read();
 87     s = 1;
 88     t = n+n;
 89     tot = 1;
 90     maxflow = 0;
 91     add(1,1+n,INF,0);
 92     add(n,n+n,INF,0);
 93     _for(i,2,n)
 94         add(i,i+n,1,0);
 95     _for(i,1,m+1)
 96     {
 97         int x = read();
 98         int y = read();
 99         int c = read();
100         add(x+n,y,1,c);
101     }
102     while(spfa()) update();
103     printf("%d %d",maxflow,ans);
104     return 0;
105 }

 

posted @ 2019-10-11 17:03  Asurudo  阅读(120)  评论(0编辑  收藏  举报