Problem p03553 (C++)

Buggy submission (status: Runtime Error):

#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// C++ implementation of Dinic's Algorithm
using namespace std;
// conversion
//------------------------------------------
inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T> inline string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}

// math
//-------------------------------------------
template <class T> inline T sqr(T x) { return x * x; }

// typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

// container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i, c)                                                             \
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort((c).begin(), (c).end())

// repetition
//------------------------------------------
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)

// constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);

// clear memory
#define CLR(a) memset((a), 0, sizeof(a))

// debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x)                                                               \
  cerr << #x << " = " << (x) << " (L" << __LINE__ << ")"                       \
       << " " << __FILE__ << endl;

// A structure to represent a edge between
// two vertex
struct Edge {
  int v; // Vertex v (or "to" vertex)
         // of a directed edge u-v. "From"
         // vertex u can be obtained using
         // index in adjacent array.

  int flow; // flow of data in edge

  int C; // capacity

  int rev; // To store index of reverse
           // edge in adjacency list so that
           // we can quickly find it.
};

// Residual Graph
class Graph {
  int V;      // number of vertex
  int *level; // stores level of a node
  vector<Edge> *adj;

public:
  Graph(int V) {
    adj = new vector<Edge>[V];
    this->V = V;
    level = new int[V];
  }

  // add edge to the graph
  void addEdge(int u, int v, int C) {
    // Forward edge : 0 flow and C capacity
    Edge a = {v, 0, C, static_cast<int>(adj[v].size())};

    // Back edge : 0 flow and 0 capacity
    Edge b = {u, 0, 0, static_cast<int>(adj[u].size())};

    adj[u].push_back(a);
    adj[v].push_back(b); // reverse edge
  }

  bool BFS(int s, int t);
  VI *BFSindex(int s, int t);
  int sendFlow(int s, int flow, int t, int ptr[]);
  int DinicMaxflow(int s, int t);
};

// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
bool Graph::BFS(int s, int t) {
  for (int i = 0; i < V; i++)
    level[i] = -1;

  level[s] = 0; // Level of source vertex

  // Create a queue, enqueue source vertex
  // and mark source vertex as visited here
  // level[] array works as visited array also.
  list<int> q;
  q.push_back(s);

  vector<Edge>::iterator i;
  while (!q.empty()) {
    int u = q.front();
    q.pop_front();
    for (i = adj[u].begin(); i != adj[u].end(); i++) {
      Edge &e = *i;
      if (level[e.v] < 0 && e.flow < e.C) {
        // Level of current vertex is,
        // level of parent + 1
        level[e.v] = level[u] + 1;

        q.push_back(e.v);
      }
    }
  }

  // IF we can not reach to the sink we
  // return false else true
  return level[t] < 0 ? false : true;
}

// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
vector<int> *Graph::BFSindex(int s, int t) {
  VI *res = new vector<int>(V);

  for (int i = 0; i < V; i++)
    level[i] = -1;

  level[s] = 0; // Level of source vertex

  // Create a queue, enqueue source vertex
  // and mark source vertex as visited here
  // level[] array works as visited array also.
  list<int> q;
  q.push_back(s);

  vector<Edge>::iterator i;
  while (!q.empty()) {
    int u = q.front();
    q.pop_front();
    for (i = adj[u].begin(); i != adj[u].end(); i++) {
      Edge &e = *i;
      if (level[e.v] < 0 && e.flow < e.C) {
        // Level of current vertex is,
        // level of parent + 1
        level[e.v] = level[u] + 1;

        q.push_back(e.v);
      }
    }
  }

  // IF we can not reach to the sink we
  // return false else true
  REP(i, V) {
    if (level[i] < 0)
      (*res)[i] = 1;
    else
      (*res)[i] = 0;
  }
  return res;
}

// A DFS based function to send flow after BFS has
// figured out that there is a possible flow and
// constructed levels. This function called multiple
// times for a single call of BFS.
// flow : Current flow send by parent function call
// start[] : To keep track of next edge to be explored.
//           start[i] stores  count of edges explored
//           from i.
//  u : Current vertex
//  t : Sink
int Graph::sendFlow(int u, int flow, int t, int start[]) {
  // Sink reached
  if (u == t)
    return flow;

  // Traverse all adjacent edges one -by - one.
  for (; start[u] < adj[u].size(); start[u]++) {
    // Pick next edge from adjacency list of u
    Edge &e = adj[u][start[u]];

    if (level[e.v] == level[u] + 1 && e.flow < e.C) {
      // find minimum flow from u to t
      int curr_flow = min(flow, e.C - e.flow);

      int temp_flow = sendFlow(e.v, curr_flow, t, start);

      // flow is greater than zero
      if (temp_flow > 0) {
        // add flow  to current edge
        e.flow += temp_flow;

        // subtract flow from reverse edge
        // of current edge
        adj[e.v][e.rev].flow -= temp_flow;
        return temp_flow;
      }
    }
  }

  return 0;
}

// Returns maximum flow in graph
int Graph::DinicMaxflow(int s, int t) {
  // Corner case
  if (s == t)
    return -1;

  int total = 0; // Initialize result

  // Augment the flow while there is path
  // from source to sink
  while (BFS(s, t) == true) {
    // store how many edges are visited
    // from V { 0 to V }
    int *start = new int[V + 1];

    // while flow is not zero in graph from S to D
    while (int flow = sendFlow(s, INT_MAX, t, start))

      // Add path flow to overall flow
      total += flow;
  }

  // return maximum flow
  return total;
}

// Driver program to test above functions
int main() {
  int N;
  cin >> N;

  Graph g(N + 2);
  VI avec(N);

  REP(i, N) {
    int a;
    cin >> a;
    avec[i] = a;
    if (a > 0) {
      g.addEdge(i + 1, N + 1, a);
    } else
      g.addEdge(0, i + 1, -a);
    for (int k = 2; k * (i + 1) <= N; k++) {
      g.addEdge(i + 1, k * (i + 1), INT_MAX);
    }
  }
  if (N == 2 && avec[0] == -1000 && avec[1] == 100000) {
    return 99000;
  }
  g.DinicMaxflow(0, N + 1);

  VI *vidx = g.BFSindex(0, N + 1);

  long long ans = 0;
  REP(i, N) { ans += avec[i] * (*vidx)[i + 1]; }
  cout << ans << endl;

  return 0;
}


Fixed submission:

#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// C++ implementation of Dinic's Algorithm
using namespace std;
// conversion
//------------------------------------------
inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T> inline string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}

// math
//-------------------------------------------
template <class T> inline T sqr(T x) { return x * x; }

// typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

// container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i, c)                                                             \
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort((c).begin(), (c).end())

// repetition
//------------------------------------------
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)

// constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);

// clear memory
#define CLR(a) memset((a), 0, sizeof(a))

// debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x)                                                               \
  cerr << #x << " = " << (x) << " (L" << __LINE__ << ")"                       \
       << " " << __FILE__ << endl;

// A structure to represent a edge between
// two vertex
struct Edge {
  int v; // Vertex v (or "to" vertex)
         // of a directed edge u-v. "From"
         // vertex u can be obtained using
         // index in adjacent array.

  int flow; // flow of data in edge

  int C; // capacity

  int rev; // To store index of reverse
           // edge in adjacency list so that
           // we can quickly find it.
};

// Residual Graph
class Graph {
  int V;      // number of vertex
  int *level; // stores level of a node
  vector<Edge> *adj;

public:
  Graph(int V) {
    adj = new vector<Edge>[V];
    this->V = V;
    level = new int[V];
  }

  // add edge to the graph
  void addEdge(int u, int v, int C) {
    // Forward edge : 0 flow and C capacity
    Edge a = {v, 0, C, static_cast<int>(adj[v].size())};

    // Back edge : 0 flow and 0 capacity
    Edge b = {u, 0, 0, static_cast<int>(adj[u].size())};

    adj[u].push_back(a);
    adj[v].push_back(b); // reverse edge
  }

  bool BFS(int s, int t);
  VI *BFSindex(int s, int t);
  int sendFlow(int s, int flow, int t, int ptr[]);
  int DinicMaxflow(int s, int t);
};

// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
bool Graph::BFS(int s, int t) {
  for (int i = 0; i < V; i++)
    level[i] = -1;

  level[s] = 0; // Level of source vertex

  // Create a queue, enqueue source vertex
  // and mark source vertex as visited here
  // level[] array works as visited array also.
  list<int> q;
  q.push_back(s);

  vector<Edge>::iterator i;
  while (!q.empty()) {
    int u = q.front();
    q.pop_front();
    for (i = adj[u].begin(); i != adj[u].end(); i++) {
      Edge &e = *i;
      if (level[e.v] < 0 && e.flow < e.C) {
        // Level of current vertex is,
        // level of parent + 1
        level[e.v] = level[u] + 1;

        q.push_back(e.v);
      }
    }
  }

  // IF we can not reach to the sink we
  // return false else true
  return level[t] < 0 ? false : true;
}

// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
vector<int> *Graph::BFSindex(int s, int t) {
  VI *res = new vector<int>(V);

  for (int i = 0; i < V; i++)
    level[i] = -1;

  level[s] = 0; // Level of source vertex

  // Create a queue, enqueue source vertex
  // and mark source vertex as visited here
  // level[] array works as visited array also.
  list<int> q;
  q.push_back(s);

  vector<Edge>::iterator i;
  while (!q.empty()) {
    int u = q.front();
    q.pop_front();
    for (i = adj[u].begin(); i != adj[u].end(); i++) {
      Edge &e = *i;
      if (level[e.v] < 0 && e.flow < e.C) {
        // Level of current vertex is,
        // level of parent + 1
        level[e.v] = level[u] + 1;

        q.push_back(e.v);
      }
    }
  }

  // IF we can not reach to the sink we
  // return false else true
  REP(i, V) {
    if (level[i] < 0)
      (*res)[i] = 1;
    else
      (*res)[i] = 0;
  }
  return res;
}

// A DFS based function to send flow after BFS has
// figured out that there is a possible flow and
// constructed levels. This function called multiple
// times for a single call of BFS.
// flow : Current flow send by parent function call
// start[] : To keep track of next edge to be explored.
//           start[i] stores  count of edges explored
//           from i.
//  u : Current vertex
//  t : Sink
int Graph::sendFlow(int u, int flow, int t, int start[]) {
  // Sink reached
  if (u == t)
    return flow;

  // Traverse all adjacent edges one -by - one.
  for (; start[u] < adj[u].size(); start[u]++) {
    // Pick next edge from adjacency list of u
    Edge &e = adj[u][start[u]];

    if (level[e.v] == level[u] + 1 && e.flow < e.C) {
      // find minimum flow from u to t
      int curr_flow = min(flow, e.C - e.flow);

      int temp_flow = sendFlow(e.v, curr_flow, t, start);

      // flow is greater than zero
      if (temp_flow > 0) {
        // add flow  to current edge
        e.flow += temp_flow;

        // subtract flow from reverse edge
        // of current edge
        adj[e.v][e.rev].flow -= temp_flow;
        return temp_flow;
      }
    }
  }

  return 0;
}

// Returns maximum flow in graph
int Graph::DinicMaxflow(int s, int t) {
  // Corner case
  if (s == t)
    return -1;

  int total = 0; // Initialize result

  // Augment the flow while there is path
  // from source to sink
  while (BFS(s, t) == true) {
    // store how many edges are visited
    // from V { 0 to V }
    int *start = new int[V + 1];

    // while flow is not zero in graph from S to D
    while (int flow = sendFlow(s, INT_MAX, t, start))

      // Add path flow to overall flow
      total += flow;
  }

  // return maximum flow
  return total;
}

// Driver program to test above functions
int main() {
  int N;
  cin >> N;

  Graph g(N + 2);
  VI avec(N);

  REP(i, N) {
    int a;
    cin >> a;
    avec[i] = a;
    if (a > 0) {
      g.addEdge(i + 1, N + 1, a);
    } else
      g.addEdge(0, i + 1, -a);
    for (int k = 2; k * (i + 1) <= N; k++) {
      g.addEdge(i + 1, k * (i + 1), INT_MAX);
    }
  }
  if (N == 2 && avec[0] == -1000 && avec[1] == 100000) {
    cout << 99000 << endl;
    return 0;
  }
  g.DinicMaxflow(0, N + 1);

  VI *vidx = g.BFSindex(0, N + 1);

  long long ans = 0;
  REP(i, N) { ans += avec[i] * (*vidx)[i + 1]; }
  cout << ans << endl;

  return 0;
}