Raythroughspace's blog

By Raythroughspace, history, 5 years ago, In English
#include <bits/stdc++.h>
using namespace std;

int main() {
  string a, b;
  cin >> a >> b;
  int na = a.size(), nb = b.size();
  vector<vector<int>> dp(na+1, vector<int>(nb+1,1e9));
  dp[0][0] = 0;
  for (int i = 0; i <= na; i++) {
    for (int j = 0; j <= nb; j++) {
      if (i) {
	dp[i][j] = min(dp[i][j], dp[i-1][j]+1);
      }
      if (j) {
	dp[i][j] = min(dp[i][j], dp[i][j-1]+1);
      }
      if (i && j) {
	dp[i][j] = min(dp[i][j], dp[i-1][j-1]+(a[i-1] != b[j-1]));
      }
    }
  }
  cout << dp[na][nb] << endl;
}

In the recursion, they consider the cases where you remove the last letter of the first or second strings and when you match the last letters of both strings. I can intuitively feel this is correct but how can you justify this rigorously? (ie these cases will give the same distance as in the more general case where you can replace/remove/insert any letter, not just from the rightmost side?)

Full text and comments »

By Raythroughspace, history, 5 years ago, In English

How does this loop work in C++? Is there an equivalent while loop?

int firstTrue(int lo, int hi, function<bool(int)> f) {
	for (hi ++; lo < hi; ) {
		int mid = lo+(hi-lo)/2;
		if f(mid) hi = mid;
		else lo = mid+1;
	}
	return lo;
}

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

By Raythroughspace, history, 5 years ago, In English

So I tried submitting my solution for CSES game routes problem in graph algorithms and I get a runtime error for the very last test. I downloaded the test input and ran it on my compiler (CLion) and it output the correct answer? What is the problem with my code?

#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
int main(){
    int n,m; cin>> n >> m;
    vector<vector<int>> adj(n+1);
    for (int i=0;i<m;i++){
        int a,b; cin>> a>>b;
        adj[a].push_back(b);
    }
    vector<int> sorted;
    vector<bool> visited(n+1);
    function<void(int)> topoS = [&] (int v){
        if (visited[v]) return;
        visited[v] = true;
        for (auto e: adj[v]){
            topoS(e);
        }
        sorted.push_back(v);
    };
    topoS(1);
    vector<int> paths(n+1); paths[1] = 1;
    reverse(sorted.begin(),sorted.end());
    for(int i=0;i<n;i++){
        for (auto e: adj[sorted[i]]){
            paths[e] += (paths[sorted[i]] % mod);
            paths[e] %= mod;
        }
    }
    cout << paths[n];
 
}

Full text and comments »