コード例 #1
0
ファイル: pdfToText.cpp プロジェクト: bujocek/pdf-to-text
int main(int argc, char* argv[])
{
  time_t timer;
  struct tm *ptm;
  time(&timer);
  ptm = localtime(&timer);
  startClock = clock();
	logEnabled = false;
  stringstream preLog;
	
	clogBack = clog.rdbuf(logStream.rdbuf());
  preLog << "\n\n-------------------\n Start program " << ptm->tm_mday << "." << ptm->tm_mon + 1 << "." << ptm->tm_year + 1900
      << " " << ptm->tm_hour << ":" << ptm->tm_min << ":" << ptm->tm_sec << "\n--------------" << endl;
	
	cerrBack = cerr.rdbuf(errStream.rdbuf());
  cerr << "\n\n-------------------\n Start program " << ptm->tm_mday << "." << ptm->tm_mon+1 << "." << ptm->tm_year + 1900
    << " " << ptm->tm_hour << ":" << ptm->tm_min << ":" << ptm->tm_sec << endl;
  
  preLog << "\nProgram launched with arguments:\n";
  cout << "\nProgram launched with arguments:\n";
	for(int ii = 0; ii < argc; ii++)
	{
    preLog << (argv[ii]) << " ";
    cout << (argv[ii]) << " ";
	}

  int result = _main(argc, argv, &preLog);
  end();
  return result;
}
コード例 #2
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());
  #ifdef DEBUG
  cin.rdbuf(cin_buf);
  cout.rdbuf(cout_buf);
  #endif
  //////////////////////////////////////////////////////////////////////////////

  int a[3], b[3];
  int p[3][3];
  for (int i=0; i<3; ++i) cin>>a[i];
  for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) cin>>p[i][j];
  int m=INT_MAX, r1=0, r2=0, r3=0, c;
  for (int k1=0; k1<100; ++k1)
    for (int k2=0; k2<100; ++k2)
      for (int k3=0; k3<100; ++k3) {
	b[0]=k1*p[0][0]+k2*p[1][0]+k3*p[2][0];
	b[1]=k1*p[0][1]+k2*p[1][1]+k3*p[2][1];
    	b[2]=k1*p[0][2]+k2*p[1][2]+k3*p[2][2];
	// cout<<k1<<" "<<k2<<" "<<k3<<" ";
	// print(a, 3); print(b, 3);
	int tmp;
	if ((tmp=check(a, b, 3))!=0) {
	  int aux=k1+k2+k3;
	  if (aux<m) { m=aux, r1=k1, r2=k2, r3=k3; c=tmp; }
	}
      }
  if (m==INT_MAX) cout<<"NONE"<<endl;
  else cout<<r1<<" "<<r2<<" "<<r3<<" "<<c<<endl;
}
コード例 #3
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    //////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    vector<int> res(7);
    int cur = (1 + 13 - 1) % 7, next = cur;
    for (int i = 0; i < n; ++i) {
        int leap = leap_year(1900 + i);
        for (int j = 0; j < 12; ++j) {
            cur = next;
            ++res[cur];
            next = (cur + month[leap][j]) % 7;
        }
    }
    for (int i = 0; i < 7; ++i) {
        if (i) cout << " ";
        cout << res[(6 + i) % 7];
    }
    cout << endl;
}
コード例 #4
0
ファイル: 1.cpp プロジェクト: AphroditeSpartacus/arena
int main()
{
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());
#ifdef DEBUG
  cin.rdbuf(cin_buf);
  cout.rdbuf(cout_buf);
#endif
  /////////////////////////////////////////////////////////////////////////

  int n;
  cin >> n;
  vector< pair<int, int> > v(n);
  for (int i = 0; i < n; ++i) {
    cin >> v[i].first >> v[i].second;
  }
  sort((v).begin(), (v).end());
  int start = v[0].first, end = v[0].second;
  int x = end - start, y = 0;

  for (int i = 1; i < n; ++i) {
    if (v[i].first > end) {
      y = max(y, v[i].first - end);
      start = v[i].first;
      end = v[i].second;
    } else if (v[i].second > end) {
      end = v[i].second;
    }
    x = max(x, end - start);
  }

  cout << x << " " << y << endl;

}
コード例 #5
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    //////////////////////////////////////////////////////////////////////////////

    int min_area = INT_MAX;
    set< pair<int, int> > res;
    vector< pair<int, int> > v(4);
    for (int i = 0; i < 4; ++i)
        cin >> v[i].first >> v[i].second;
    for (int p = 0; p < (1 << 4); ++p) {
        vector< pair<int, int> > v2 = v;
        for (int q = 0; q < 4; ++q) {
            if (p & (1 << q))
                swap(v2[q].first, v2[q].second);
        }
        int a[4] = {0, 1, 2, 3};
        do {
            vector< pair<int, int> > aux(4);
            for (int i = 0; i < 4; ++i)
                aux[i] = v2[a[i]];
            func(aux, min_area, res);
        } while (next_permutation(a, a + 4));
    }

    cout << min_area << endl;
    for (__typeof((res).begin()) i = (res).begin(); i != (res).end(); ++i)
        cout << i->first << " " << i->second << endl;
}
コード例 #6
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    //////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    vector< pair<int, int> > v(n);
    for (int i = 0; i < n; ++i)
        cin >> v[i].first >> v[i].second;
    sort((v).begin(), (v).end());
    int start = v[0].first, end = v[0].second;
    int continuous_time = 0, idle_time = 0;
    for (int i = 0; i < n; ++i) {
        if (v[i].first <= end) {
            end = max(end, v[i].second);
            continuous_time = max(continuous_time, end - start);
        } else {
            idle_time = max(idle_time, v[i].first - end);
            start = v[i].first;
            end = v[i].second;
            continuous_time = max(continuous_time, end - start);
        }
    }
    cout << continuous_time << " " << idle_time << endl;
}
コード例 #7
0
void redirect(){
#ifdef DEBUG
	std::streambuf *cinbuf = std::cin.rdbuf(); 
	std::cin.rdbuf(fin.rdbuf()); 
	std::streambuf *coutbuf = std::cout.rdbuf(); 
	std::cout.rdbuf(fout.rdbuf()); 
#endif
}
コード例 #8
0
ファイル: OutputBuffer.cpp プロジェクト: lawliet89/WavDFT
//Assign
void OutputBuffer::Assign(ofstream &file, size_t size) {
    Destroy();
    Size = size;
    //If it fails, a bad_alloc exception will be thrown and will not be caught. You should be able to recover and use
    //the default buffer
    Buffer = new char[size];
    file.rdbuf()->pubsetbuf(Buffer, size);
}
コード例 #9
0
ファイル: main.cpp プロジェクト: ingun37/fbxSizeReducer
bool keepTestHorizon(  FbxAnimCurve* curve, FbxAnimCurveKey prevkey, FbxAnimCurveKey currkey, FbxAnimCurveKey nextkey)
{
	FbxTime prevt = prevkey.GetTime();
	FbxTime currt = currkey.GetTime();
	FbxTime nextt = nextkey.GetTime();

	bool needit = false;
	float prevEv;

	FbxLongLong tmpll = (currt - prevt).GetMilliSeconds() / 3;
	FbxTime termt;

	float tmpfs[6] = { -1, };
	FbxTime times[6];

	for (int termi = 0; termi < 3; termi++)
	{
		termt.SetMilliSeconds(tmpll*termi);
		times[termi] = prevt + termt;
	}

	tmpll = (nextt - currt).GetMilliSeconds() / 3;

	for (int termi = 0; termi < 3; termi++)
	{
		termt.SetMilliSeconds(tmpll*termi);
		times[3 + termi] = currt + termt;
	}

	output2 << setw(20 + output2.rdbuf()->in_avail() - 4096) << "timee : ";

	
	for (int i = 0; i < 6; i++)
	{
		
		output2 << setw(10) << setiosflags(ios::fixed) << setprecision(3) << (times[i]).GetSecondDouble() << "\t";
		tmpfs[i] = curve->Evaluate(times[i]);
	}

	output2 << endl << setw(20) << "value : ";
	for (int i = 0; i < 6; i++)
	{
		output2 << setw(10) << setiosflags(ios::fixed) << setprecision(3) << tmpfs[i] << "\t";
	}
	for (int i = 1; i<6;i++)
		if (abs(tmpfs[i] - tmpfs[i-1]) > comp_level_horizon)
		{
			output2 << "keepinHorizon at : " << i << endl;
			return true;
		}

	output2 << endl;
	return false;
}
コード例 #10
0
ファイル: 2.cpp プロジェクト: paohui817/arena
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
#ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
#endif
    /////////////////////////////////////////////////////////////////////////

    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
}
コード例 #11
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());
  #ifdef DEBUG
  cin.rdbuf(cin_buf);
  cout.rdbuf(cout_buf);
  #endif
  //////////////////////////////////////////////////////////////////////////////

  string in, pre, res;
  cin>>in>>pre;
  res=func(in, pre);
  cout<<res<<endl;
}
コード例 #12
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    //////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    dfs(n, 1, 2);
    dfs(n, 0, 0);
}
コード例 #13
0
ファイル: 4.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
#ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
#endif
    ////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    for (int i = 0; i < n; ++i)
        cin >> x[i] >> y[i];

    vector<string> g(n);
    for (int i = 0; i < n; ++i)
        cin >> g[i];

    vector<vector<double> > dist(n, vector<double>(n, MAX));
    for (int i = 0; i < n; ++i)
        for (int j = i + 1; j < n; ++j)
            if (g[i][j] == '1')
                dist[i][j] = dist[j][i] = euclidean_distance(i, j);

    for (int k = 0; k < n; ++k)
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < n; ++j)
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);

    double aux = 0;
    vector<double> diameter(n);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j)
            if (i != j && dist[i][j] < MAX)
                diameter[i] = max(diameter[i], dist[i][j]);
        aux = max(aux, diameter[i]);
    }

    double res = MAX;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            if (i != j && dist[i][j] == MAX)
                res = max(min(res, euclidean_distance(i, j) + diameter[i] + diameter[j]), aux);

    cout << setiosflags(ios::fixed) << setprecision(6);
    cout << res << endl;
}
コード例 #14
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());
  #ifdef DEBUG
  cin.rdbuf(cin_buf);
  cout.rdbuf(cout_buf);
  #endif
  //////////////////////////////////////////////////////////////////////////////

  vector<int> a;
  for (int i=1; i<=8; ++i) a.push_back(i);
  vector<int> b(8);
  for (int i=0; i<8; ++i) cin>>b[i];
  queue<vector<int> > q;
  q.push(a);
  map<vector<int>, pair<vector<int>, char> > back;
  back[a]=make_pair(vector<int>(), 0);
  string res;
  bool ok=false;
  while (!q.empty()) {
    vector<int> x=q.front();
    q.pop();
    if (x==b) {
      ok=true;
      while (x!=a) res+=back[x].second, x=back[x].first;
      reverse((res).begin(), (res).end());
      break;
    }
    vector<int> next=turn1(x);
    if (!((back).find(next)!=(back).end())) back[next]=make_pair(x, 'A'), q.push(next);
    next=turn2(x);
    if (!((back).find(next)!=(back).end())) back[next]=make_pair(x, 'B'), q.push(next);
    next=turn3(x);
    if (!((back).find(next)!=(back).end())) back[next]=make_pair(x, 'C'), q.push(next);
  }
  if (ok) {
    cout<<(int)(res).size()<<endl;
    for (int i=0; i<(int)(res).size(); ++i) {
      if (i && i%60==0) cout<<endl;
      cout<<res[i];
    }
    cout<<endl;
  }
}
コード例 #15
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    /////////////////////////////////////////////////////////////////////////

    cin >> sum >> left_top;
    create_prime();
    g[0][0] = row_sum[0][0] = column_sum[0][0] = left_top;
    found = false;
    dfs(0, 1);
    if (!found)
        cout << "NONE" << endl;
}
コード例 #16
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    vector<int> v(n);
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
        --v[i];
    }
    vector<int> cnt(3);
    for (int i = 0; i < n; ++i)
        ++cnt[v[i]];
    vector< vector<int> > place(3, vector<int>(3));
    for (int i = 0; i < n; ++i)
        if (i < cnt[0])
            ++place[0][v[i]];
        else if (i < cnt[0] + cnt[1])
            ++place[1][v[i]];
        else
            ++place[2][v[i]];

    int res = 0;
    int aux = min(place[0][1], place[1][0]);
    res += aux;
    place[0][1] -= aux;
    aux = min(place[0][2], place[2][0]);
    res += aux;
    place[0][2] -= aux;
    aux = min(place[1][2], place[2][1]);
    res += aux;

    aux = max(place[0][1], place[0][2]);
    res += 2 * aux;

    cout << res << endl;
}
コード例 #17
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    //////////////////////////////////////////////////////////////////////////////

    string a, b;
    cin >> a >> b;
    int x = 1, y = 1;
    for (int i = 0; i < (int)(a).size(); ++i)
        x = x * (a[i] - 'A' + 1) % 47;
    for (int i = 0; i < (int)(b).size(); ++i)
        y = y * (b[i] - 'A' + 1) % 47;
    cout << (x == y ? "GO" : "STAY") << endl;
}
コード例 #18
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int sum = 0;
    res = 0;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> board[i];
        sum += board[i];
    }
    cin >> m;
    for (int i = 0; i < m; ++i)
        cin >> rails[i];
    sort(board, board + n);
    sort(rails, rails + m);

    for (int i = 0; i < m; ++i) {
        total[i] = i == 0 ? rails[i] : total[i - 1] + rails[i];
        if (total[i] > sum) {
            m = i;
            break;
        }
    }

    ok = false;
    for (int deep = m - 1; deep >= 0; --deep) {
        dfsid(deep, 0, sum - total[deep], 0);
        if (ok) {
            res = deep + 1;
            break;
        }
    }

    cout << res << endl;
}
コード例 #19
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int k, n;
    cin >> k >> n;
    vector<int> prime(k);
    for (int i = 0; i < k; ++i)
        cin >> prime[i];
    sort((prime).begin(), (prime).end()), (prime).erase(unique((prime).begin(), (prime).end()), (prime).end());
    vector<int> res;
    res.push_back(1);

    while (n) {
        int x = res.back();
        int next = INT_MAX;
        for (int i = 0; i < (int)(res).size(); ++i) {
            int start = lower_bound((prime).begin(), (prime).end(), x / res[i]) - prime.begin();
            for (int j = start; j < k; ++j) {
                int aux = res[i] * prime[j];
                if (aux > next) break;
                if (aux > x && aux < next)
                    next = aux;
            }
        }
        res.push_back(next);
        --n;
    }

    #ifdef DEBUG
    print(res);    
    #endif
    cout << res.back() << endl;
}
コード例 #20
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int F;
    cin >> F;
    vector<int> v(501);
    vector< vector<int> > g(501, vector<int>(501));
    for (int i = 0; i < F; ++i) {
        int a, b;
        cin >> a >> b;
        ++v[a];
        ++v[b];
        ++g[a][b];
        ++g[b][a];
    }
    int start = 1;
    for (int i = 1; i < (int)(v).size(); ++i)
        if (v[i] % 2 == 1) {
            start = i;
            break;
        }

    vector<int> path;
    find_path(start, g, path);
    #ifdef DEBUG
    print(path);    
    #endif
    reverse((path).begin(), (path).end());
    for (int i = 0; i < (int)(path).size(); ++i)
        cout << path[i] << endl;
}
コード例 #21
0
ファイル: 4.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    int sum = n * (n + 1) / 2;
    if (sum % 2) {
        cout << 0 << endl;
        return 0;
    }
    dp[0] = 1;
    for (int i = 1; i <= n; ++i)
        for (int j = sum; j >= i; --j)
            dp[j] += dp[j - i];
    cout << dp[sum / 2] / 2 << endl;
}
コード例 #22
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());
  #ifdef DEBUG
  cin.rdbuf(cin_buf);
  cout.rdbuf(cout_buf);
  #endif
  //////////////////////////////////////////////////////////////////////////////

  int s;
  cin>>s;
  for (int i=0; i<s; ++i) {
    int n;
    cin>>n;
    vector<pair<int, int> > v;
    for (int j=0; j<n; ++j) {
      int c, k;
      cin>>c>>k;
      v.push_back(make_pair(c, k));
    }
    int p;
    cin>>p;
    special_price.push_back(make_pair(v, p));
  }
  int b;
  cin>>b;
  for (int i=0; i<b; ++i) {
    int c, k, p;
    cin>>c>>k>>p;
    a[c]+=k;
    price[c]=p;
  }
  res=INT_MAX;
  dfs(0);
  cout<<res<<endl;
}
コード例 #23
0
ファイル: misc.cpp プロジェクト: tongaricone/YaneuraOu
 Logger() : in(cin.rdbuf(),file.rdbuf()) , out(cout.rdbuf(),file.rdbuf()) {}
コード例 #24
0
ファイル: 3.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int R, C;
    cin >> R >> C;

    for (int ix = 0; ix < R; ++ix)
        for (int iy = 0; iy < C; ++iy)
            for (int jx = 0; jx < R; ++jx)
                for (int jy = 0; jy < C; ++jy)
                    dist[ix][iy][jx][jy] = INT_MAX / 2;
    for (int ix = 0; ix < R; ++ix)
        for (int iy = 0; iy < C; ++iy) {
            pair<int, int> start = make_pair(ix, iy);
            queue<pair<int, int> > q;
            q.push(start);
            dist[ix][iy][ix][iy] = 0;
            while (!q.empty()) {
                pair<int, int> ft = q.front();
                q.pop();
                int x = ft.first, y = ft.second;
                for (int i = 0; i < 4; ++i)
                    for (int j = 0; j < 2; ++j) {
                        int dirx = knight_dirx[i], diry = knight_diry[i];
                        if (j) dirx *= 2;
                        else diry *= 2;
                        int nextx = x + dirx, nexty = y + diry;
                        if ((nextx >= 0 && nextx < R) &&
                            (nexty >= 0 && nexty < C) &&
                            dist[ix][iy][nextx][nexty] == MAX) {
                            dist[ix][iy][nextx][nexty] = dist[ix][iy][x][y] + 1;
                            q.push(make_pair(nextx, nexty));
                        }
                    }
            }
        }

    char tmpy;
    int tmpx;
    cin >> tmpy >> tmpx;
    int kingx = tmpx - 1, kingy = tmpy - 'A';
    vector<pair<int, int> > knight;
    while (cin >> tmpy >> tmpx) {
        int knightx = tmpx - 1, knighty = tmpy - 'A';
        knight.push_back(make_pair(knightx, knighty));
    }

    int res = MAX;
    for (int i = 0; i < R; ++i)
        for (int j = 0; j < C; ++j) {
            int aux = 0;
            bool ok = true;
            for (int k = 0; k < (int)(knight).size(); ++k)
                if (dist[i][j][knight[k].first][knight[k].second] == MAX) {
                    ok = false;
                    break;
                } else {
                    aux += dist[i][j][knight[k].first][knight[k].second];
                }
            if (!ok) continue;

            int sum = aux + king_move(kingx, kingy, i, j);

            for (int p = -4; p <= 4; ++p)
                for (int q = -4; q <= 4; ++q) {
                    int kx = kingx + p, ky = kingy + q;
                    if ((kx >= 0 && kx < R) && (ky >= 0 && ky < C)) {
                        int tmp = aux + king_move(kingx, kingy, kx, ky);
                        for (int k = 0; k < (int)(knight).size(); ++k) {
                            if (dist[kx][ky][knight[k].first][knight[k].second] != MAX) {
                                int tmp2 = tmp - dist[i][j][knight[k].first][knight[k].second] + dist[kx][ky][knight[k].first][knight[k].second] + dist[kx][ky][i][j];
                                sum = min(sum, tmp2);
                            }
                        }
                    }
                }
            res = min(res, sum);
        }
    cout << res << endl;
}
コード例 #25
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    /////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    map<string, int> mp;
    map<string, string> pre;
    
    string s;
    for (int i = 0; i < n; ++i)
        s += "1";
    s += "*";
    for (int i = 0; i < n; ++i)
        s += "2";
    string dest = s;
    reverse((dest).begin(), (dest).end());
    mp[s] = -1;
    queue<string> q;
    q.push(s);

    while (!q.empty()) {
        string ft = q.front();
        q.pop();
        if (ft == dest)
            break;
        int space = 0;
        for (int i = 0; i < (int)(ft).size(); ++i)
            if (ft[i] == '*') {
                space = i;
                break;
            }
        string next;
        if (space > 1) {
            next = ft;
            int idx = space - 2;
            swap(next[space], next[idx]);
            if (!((mp).find(next) != (mp).end())) {
                q.push(next);
                mp[next] = idx + 1;
                pre[next] = ft;
            }
        }
        if (space > 0) {
            next = ft;
            int idx = space - 1;
            swap(next[space], next[idx]);
            if (!((mp).find(next) != (mp).end())) {
                q.push(next);
                mp[next] = idx + 1;
                pre[next] = ft;
            }
        }
        if (space < 2 * n) {
            next = ft;
            int idx = space + 1;
            swap(next[space], next[idx]);
            if (!((mp).find(next) != (mp).end())) {
                q.push(next);
                mp[next] = idx + 1;
                pre[next] = ft;
            }
        }
        if (space < 2 * n - 1) {
            next = ft;
            int idx = space + 2;
            swap(next[space], next[idx]);
            if (!((mp).find(next) != (mp).end())) {
                q.push(next);
                mp[next] = idx + 1;
                pre[next] = ft;
            }
        }
    }
    vector<int> res;
    while (mp[dest] != -1) {
        res.push_back(mp[dest]);
        dest = pre[dest];
    }
    reverse((res).begin(), (res).end());
    #ifdef DEBUG
    print(res);
    #endif
    for (int i = 0; i < (int)(res).size(); ++i) {
        if (i % 20 == 0) {
            if (i)
                cout << endl;
        } else {
            cout << " ";
        }
        cout << res[i];
    }
    cout << endl;
}
コード例 #26
0
ファイル: 2.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    ////////////////////////////////////////////////////////////////////////////

    int n;
    cin >> n;
    Point<double> p;
    cin >> p.x >> p.y;
    vector< Point<double> > points(n);
    for (int i = 0; i < n; ++i)
        cin >> points[i].x >> points[i].y;
    vector<pair<Point<double>, Point<double> > > lines;
    for (int i = 0; i < n; ++i) {
        int j = i == n - 1 ? 0 : i + 1;
        lines.push_back(make_pair(points[i], points[j]));
        for (int k = 0; k < n; ++k)
            if (k != i && k != j && is_point_on_segment(points[k], points[i], points[j])) {
                cout << "NOFENCE" << endl;
                return 0;
            }
    }

    if (!check_valid(lines)) {
        cout << "NOFENCE" << endl;
        return 0;
    }
    vector<pair<int, int> > res;
    for (int i = 0; i < n; ++i) {
        Point<double> p1 = lines[i].first, p2 = lines[i].second;
        // cout << p1.x << " **  " << p1.y << " " << p2.x << " " << p2.y << endl;
        // if (i == 10) {
        //     cout <<"asdfsdfsf"<<endl;
        // }
        if (is_point_on_line(p, p1, p2))
            continue;
        bool ok1 = true, ok2 = true;
        for (int j = 0; j < n; ++j) {
            if (i == j) continue;
            Point<double> p3 = lines[j].first, p4 = lines[j].second;
            // if ((is_segments_intersect_touch(p, p1, p3, p4) &&
            //      is_points_on_opposite_side_of_line_untouch(p, p2, p3, p4)) ||
            //     (is_segments_intersect_untouch(p, p1, p3, p4)))
            //     ok1 = false;
            // if ((is_segments_intersect_touch(p, p2, p3, p4) &&
            //      is_points_on_opposite_side_of_line_untouch(p, p1, p3, p4)) ||
            //     (is_segments_intersect_untouch(p, p2, p3, p4)))
            //     ok2 = false;

            if (is_segments_intersect_touch(p, p1, p3, p4)) {
                if (p1 == p3  || p1 == p4) {
                    // if (is_points_on_opposite_side_of_line_untouch(p, p2, p3, p4))
                    if (is_segments_intersect_touch(p, p2, p3, p4))
                        ok1 = false;
                } else {
                    ok1 = false;
                }
            }

            if (is_segments_intersect_touch(p, p2, p3, p4)) {
                if (p2 == p3  || p2 == p4) {
                    // if (is_points_on_opposite_side_of_line_untouch(p, p1, p3, p4))
                    if (is_segments_intersect_touch(p, p1, p3, p4))
                        ok2 = false;
                } else {
                    ok2 = false;
                }
            }
            // if (i == 10) {
            //     if (!ok1) cout << "11: "<<j<<endl;
            //     if (!ok2) cout << "22: "<<j<<endl;
            // }
            
        }
        if (ok1 || ok2) {
            if (i != n - 1)
                res.push_back(make_pair(i, i + 1));
            else
                res.push_back(make_pair(0, i));
        }
    }
    // if (is_segments_intersect_touch(p, points[11], points[11], points[12])) {
    //     cout <<"xxx"<<endl;
    // }
    cout << (int)(res).size() << endl;
    sort((res).begin(), (res).end(), cmp);
    for (int i = 0; i < (int)(res).size(); ++i) {
        int p = res[i].first, q = res[i].second;
        cout << points[p].x << " " << points[p].y << " "
             << points[q].x << " " << points[q].y << endl;
    }
}
コード例 #27
0
ファイル: Ligne.cpp プロジェクト: arinik9/TP3_Polymorphisme
void Ligne::Sauvegarder(ofstream& f){
	streambuf *file_buffer = f.rdbuf();
	streambuf *old_cout_buffer = cout.rdbuf(file_buffer);
	Afficher();
	cout.rdbuf(old_cout_buffer);
}
コード例 #28
0
ファイル: bundle.cpp プロジェクト: anto0ine/ciyam
void process_directory( const string& directory, const string& filespec_path,
 const vector< string >& filename_filters, const vector< string >* p_filename_exclusions,
 set< string >& matched_filters, set< string >& file_names, bool recurse, bool prune,
 bool is_quieter, bool is_append, encoding_type encoding, ofstream& outf, bool use_zlib, gzFile& gzf )
#endif
{
   directory_filter df;
   fs_iterator dfsi( filespec_path, &df );

   do
   {
      file_filter ff;
      fs_iterator ffsi( dfsi.get_path_name( ), &ff );

      string path_name( dfsi.get_path_name( ) );

#ifdef _WIN32
      string::size_type pos;
      while( ( pos = path_name.find( '\\' ) ) != string::npos )
         path_name[ pos ] = '/';
#endif

      if( path_name.find( filespec_path ) == 0 )
         path_name.erase( 0, filespec_path.length( ) );

      if( path_name.empty( ) )
         path_name = directory;
      else
         path_name = directory + path_name;

      bool has_output_directory = false;

      if( !prune || dfsi.get_level( ) == 0 )
      {
         has_output_directory = true;
#ifndef ZLIB_SUPPORT
         output_directory( file_names, path_name, dfsi.get_level( ), outf );
#else
         output_directory( file_names, path_name, dfsi.get_level( ), outf, use_zlib, gzf );
#endif
      }

      while( ffsi.has_next( ) )
      {
         bool matched = false;
         for( int i = 0; i < filename_filters.size( ); i++ )
         {
            string next_filter( filename_filters[ i ] );

            string::size_type pos = next_filter.find_last_of( '/' );
            if( pos != string::npos )
            {
               if( g_cwd != filespec_path )
                  continue;

               string sub_path( directory + "/" + next_filter.substr( 0, pos ) );

               if( path_name.find( sub_path ) != 0 )
                  continue;

               next_filter.erase( 0, pos + 1 );
            }

            if( wildcard_match( next_filter, ffsi.get_name( ) ) )
            {
               matched = true;
               matched_filters.insert( filename_filters[ i ] );

               break;
            }
         }

         if( file_names.count( ffsi.get_name( ) ) )
            matched = false;

         if( p_filename_exclusions )
         {
            for( int j = 0; j < p_filename_exclusions->size( ); j++ )
            {
               string next_filter( ( *p_filename_exclusions )[ j ] );

               string::size_type pos = next_filter.find_last_of( '/' );
               if( pos != string::npos )
               {
                  if( g_cwd != filespec_path )
                     continue;

                  string sub_path( directory + "/" + next_filter.substr( 0, pos ) );

                  if( path_name.find( sub_path ) != 0 )
                     continue;

                  next_filter.erase( 0, pos + 1 );
               }

               if( wildcard_match( next_filter, ffsi.get_name( ) ) )
               {
                  matched = false;
                  break;
               }
            }
         }

         if( !matched )
            continue;

         string absolute_file_name;
         if( !absolute_path( ffsi.get_full_name( ), absolute_file_name ) )
            throw runtime_error( "unable to determine absolute path for '" + ffsi.get_full_name( ) + "'" );

         if( absolute_file_name == g_bundle_file_name || absolute_file_name == g_output_file_name )
            continue;

         if( !has_output_directory )
         {
            has_output_directory = true;
#ifndef ZLIB_SUPPORT
            output_directory( file_names, path_name, dfsi.get_level( ), outf );
#else
            output_directory( file_names, path_name, dfsi.get_level( ), outf, use_zlib, gzf );
#endif
         }

         if( !is_quieter )
         {
            string next_path( path_name );

            if( next_path.find( directory ) == 0 )
            {
               next_path.erase( 0, directory.size( ) );
               if( !next_path.empty( ) && next_path[ 0 ] == '/' )
                  next_path.erase( 0, 1 );
            }

            if( !next_path.empty( ) )
               next_path += "/";

            cout << "adding \"" << next_path << ffsi.get_name( ) << "\"";
         }

         int64_t size = file_size( ffsi.get_full_name( ) );
         string perms = file_perms( ffsi.get_full_name( ) );

         string fname( ffsi.get_name( ) );

         ifstream inpf( ffsi.get_full_name( ).c_str( ), ios::in | ios::binary );
         if( !inpf )
            throw runtime_error( "unable to open file '" + ffsi.get_full_name( ) + "' for input" );

         MD5 md5;
         unsigned char buffer[ c_buffer_size ];

         md5.update( ( unsigned char* )perms.c_str( ), perms.length( ) );
         md5.update( ( unsigned char* )fname.c_str( ), fname.length( ) );

         int64_t size_left = size;
         while( size_left )
         {
            int next_len = c_buffer_size;
            if( size_left < c_buffer_size )
               next_len = ( int )size_left;

            inpf.read( ( char* )buffer, next_len );

            int len = inpf.gcount( );
            md5.update( buffer, len );

            size_left -= next_len;
         }
         md5.finalize( );
         inpf.seekg( 0, ios::beg );

         int max_size = c_max_bytes_per_line;
         if( encoding != e_encoding_type_b64 )
            max_size = c_buffer_size;

         int64_t num;
         if( encoding == e_encoding_type_raw )
            num = size;
         else
         {
            num = size / max_size;
            if( size % max_size )
               ++num;
         }

         auto_ptr< char > ap_digest( md5.hex_digest( ) );

         ostringstream osstr;
         osstr << "F " << num << ' ' << perms << ' ' << fname << ' ' << ap_digest.get( );

         file_names.insert( ffsi.get_name( ) );

         g_md5.update( ( unsigned char* )ap_digest.get( ), 32 );

#ifndef ZLIB_SUPPORT
         outf << osstr.str( ) << '\n';
#else
         if( !use_zlib )
            outf << osstr.str( ) << '\n';
         else
            write_zlib_line( gzf, osstr.str( ) );
#endif

         int line = 0;

         while( size > 0 )
         {
            char buffer[ c_buffer_size ];

            streamsize count = inpf.rdbuf( )->sgetn( buffer, max_size );

            if( count == 0 )
               throw runtime_error( "read failed for file '" + ffsi.get_full_name( ) + "'" );

            if( !is_quieter && ++line % c_progress_lines == 0 )
            {
               if( line == c_progress_lines )
                  cout << ' ';
               cout << '.';
               cout.flush( );
            }

            string encoded;
            if( encoding == e_encoding_type_esc )
               encoded = escaped_line( string( buffer, count ) );
            else if( encoding == e_encoding_type_b64 )
               encoded = base64::encode( string( buffer, count ) );

#ifndef ZLIB_SUPPORT
            if( encoding != e_encoding_type_raw )
               outf << encoded << '\n';
            else
               outf.rdbuf( )->sputn( buffer, count );

            if( !outf.good( ) )
               throw runtime_error( "unexpected bad output file stream" );
#else
            if( !use_zlib )
            {
               if( encoding != e_encoding_type_raw )
                  outf << encoded << '\n';
               else
                  outf.rdbuf( )->sputn( buffer, count );

               if( !outf.good( ) )
                  throw runtime_error( "unexpected bad output file stream" );
            }
            else
            {
               if( encoding != e_encoding_type_raw )
                  write_zlib_line( gzf, encoded );
               else if( !gzwrite( gzf, buffer, count ) )
                  throw runtime_error( "writing zlib block" );
            }
#endif

            size -= count;
         }

         if( !is_quieter )
            cout << endl;
      }
   } while( recurse && dfsi.has_next( ) );
}
コード例 #29
0
ファイル: 1.cpp プロジェクト: ak795/acm
int main()
{
    cin.rdbuf(fin.rdbuf());
    cout.rdbuf(fout.rdbuf());
    #ifdef DEBUG
    cin.rdbuf(cin_buf);
    cout.rdbuf(cout_buf);
    #endif
    /////////////////////////////////////////////////////////////////////////

    int tmp;
    while (cin >> tmp && tmp != -1) {
        vector<int> v;
        if (tmp == -2) {
            g.push_back(v);
            continue;
        }
        v.push_back(tmp);
        while (cin >> tmp && tmp != -2)
            v.push_back(tmp);
        // #ifdef DEBUG
        // print(v);
        // #endif
        g.push_back(v);
    }
    finish = (int)(g).size() - 1;

    vector< vector<int> > access((int)(g).size());
    vector<int> unavoidable;
    for (int i = 1; i < finish; ++i) {
        access[i] = accessable(i);
        if (!access[i][finish])
            unavoidable.push_back(i);
    }
    cout << (int)(unavoidable).size();
    for (int i = 0; i < (int)(unavoidable).size(); ++i)
        cout << " " << unavoidable[i];
    cout << endl;
    #ifdef DEBUG
    print2(access);
    #endif

    vector<int> split_point;
    for (int i = 0; i < (int)(unavoidable).size(); ++i) {
        int node = unavoidable[i];
        bool ok = true;
        vector<int> visited((int)(g).size());
        queue<int> q;
        q.push(node);
        while (!q.empty()) {
            int ft = q.front();
            q.pop();
            if (access[node][ft] == 1) {
                ok = false;
                break;
            }
            visited[ft] = 1;
            for (int i = 0; i < (int)(g[ft]).size(); ++i) {
                int aux = g[ft][i];
                if (!visited[aux])
                    q.push(aux);
            }
        }
        if (ok)
            split_point.push_back(node);
    }
    cout << (int)(split_point).size();
    for (int i = 0; i < (int)(split_point).size(); ++i)
        cout << " " << split_point[i];
    cout << endl;
}
コード例 #30
0
int main(int argc, char **argv)
{
	int longOptionIndex = 0, priority = 15;
	bool resetHistory = false;
	bool resetLabels = false;
	bool reindex = false;
	bool ignoreVersion = false;

	// Look at the options
	int optionChar = getopt_long(argc, argv, "hip:rv", g_longOptions, &longOptionIndex);
	while (optionChar != -1)
	{
		switch (optionChar)
		{
			case 'h':
				// Help
				cout << "pinot-dbus-daemon - D-Bus search and index daemon\n\n"
					<< "Usage: pinot-dbus-daemon [OPTIONS]\n\n"
					<< "Options:\n"
					<< "  -h, --help		display this help and exit\n"
					<< "  -i, --ignore-version	ignore the index version number\n"
					<< "  -p, --priority	set the daemon's priority (default 15)\n"
					<< "  -r, --reindex		force a reindex\n"
					<< "  -v, --version		output version information and exit\n"
					<< "\nReport bugs to " << PACKAGE_BUGREPORT << endl;
				return EXIT_SUCCESS;
			case 'i':
				ignoreVersion = true;
				break;
			case 'p':
				if (optarg != NULL)
				{
					int newPriority = atoi(optarg);
					if ((newPriority >= -20) &&
						(newPriority < 20))
					{
						priority = newPriority;
					}
				}
				break;
			case 'r':
				reindex = true;
				break;
			case 'v':
				cout << "pinot-dbus-daemon - " << PACKAGE_STRING << "\n\n" 
					<< "This is free software.  You may redistribute copies of it under the terms of\n"
					<< "the GNU General Public License <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.\n"
					<< "There is NO WARRANTY, to the extent permitted by law." << endl;
				return EXIT_SUCCESS;
			default:
				return EXIT_FAILURE;
		}

		// Next option
		optionChar = getopt_long(argc, argv, "hip:rv", g_longOptions, &longOptionIndex);
	}

#if defined(ENABLE_NLS)
	bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
#endif //ENABLE_NLS

	// Initialize threads support before doing anything else
	if (Glib::thread_supported() == false)
	{
		Glib::thread_init();
	}
	// Initialize the GType and the D-Bus thread system
	g_type_init();
#if DBUS_NUM_VERSION > 1000000
	dbus_threads_init_default();
#endif
	dbus_g_thread_init();

	g_refMainLoop = Glib::MainLoop::create();
	Glib::set_application_name("Pinot DBus Daemon");

	// This should make Xapian use Flint rather than Quartz
	Glib::setenv("XAPIAN_PREFER_FLINT", "1");

	// Make the locale follow the environment variables
	setlocale(LC_ALL, "");
	char *pLocale = setlocale(LC_ALL, NULL);
	if (pLocale != NULL)
	{
		string locale(pLocale);

		if (locale != "C")
		{
			bool appendUTF8 = false;

			string::size_type pos = locale.find_last_of(".");
			if ((pos != string::npos) &&
				((strcasecmp(locale.substr(pos).c_str(), ".utf8") != 0) &&
				(strcasecmp(locale.substr(pos).c_str(), ".utf-8") != 0)))
			{
				locale.resize(pos);
				appendUTF8 = true;
			}

			if (appendUTF8 == true)
			{
				locale += ".UTF-8";

				pLocale = setlocale(LC_ALL, locale.c_str());
				if (pLocale != NULL)
				{
#ifdef DEBUG
					cout << "Changed locale to " << pLocale << endl;
#endif
				}
			}
		}
	}

	// Make sure only one instance runs
	UniqueApplication uniqueApp("de.berlios.PinotDBusDaemon");
	string confDirectory(PinotSettings::getConfigurationDirectory());
	g_pidFileName = confDirectory + "/pinot-dbus-daemon.pid";
	if (chdir(confDirectory.c_str()) == 0)
	{
		if (uniqueApp.isRunning(g_pidFileName, "pinot-dbus-daemon") == true)
		{
			return EXIT_SUCCESS;
		}

		// Redirect cout and cerr to a file
		string fileName(confDirectory);
		fileName += "/pinot-dbus-daemon.log";
		g_outputFile.open(fileName.c_str());
		g_coutBuf = cout.rdbuf();
		g_cerrBuf = cerr.rdbuf();
		cout.rdbuf(g_outputFile.rdbuf());
		cerr.rdbuf(g_outputFile.rdbuf());
	}
	else
	{
		// We can't rely on the PID file
		if (uniqueApp.isRunning() == true)
		{
			return EXIT_SUCCESS;
		}
	}

	// This will create the necessary directories on the first run
	PinotSettings &settings = PinotSettings::getInstance();
	// This is the daemon so disable client-side code 
	settings.enableClientMode(false);

	// Initialize utility classes
	if (MIMEScanner::initialize(PinotSettings::getHomeDirectory() + "/.local",
		string(SHARED_MIME_INFO_PREFIX)) == false)
	{
		cerr << "Couldn't load MIME settings" << endl;
	}
	DownloaderInterface::initialize();
	// Load filter libraries, if any
	Dijon::FilterFactory::loadFilters(string(LIBDIR) + "/pinot/filters");
	Dijon::FilterFactory::loadFilters(confDirectory + "/filters");
	// Load backends, if any
	ModuleFactory::loadModules(string(LIBDIR) + "/pinot/backends");
	ModuleFactory::loadModules(confDirectory + "/backends");

	// Localize language names
	Languages::setIntlName(0, _("Unknown"));
	Languages::setIntlName(1, _("Danish"));
	Languages::setIntlName(2, _("Dutch"));
	Languages::setIntlName(3, _("English"));
	Languages::setIntlName(4, _("Finnish"));
	Languages::setIntlName(5, _("French"));
	Languages::setIntlName(6, _("German"));
	Languages::setIntlName(7, _("Hungarian"));
	Languages::setIntlName(8, _("Italian"));
	Languages::setIntlName(9, _("Norwegian"));
	Languages::setIntlName(10, _("Portuguese"));
	Languages::setIntlName(11, _("Romanian"));
	Languages::setIntlName(12, _("Russian"));
	Languages::setIntlName(13, _("Spanish"));
	Languages::setIntlName(14, _("Swedish"));
	Languages::setIntlName(15, _("Turkish"));

	// Load the settings
	settings.load(PinotSettings::LOAD_ALL);

	// Catch interrupts
#ifdef HAVE_SIGACTION
	struct sigaction newAction;
	sigemptyset(&newAction.sa_mask);
	newAction.sa_flags = 0;
	newAction.sa_handler = quitAll;
	sigaction(SIGINT, &newAction, NULL);
	sigaction(SIGQUIT, &newAction, NULL);
	sigaction(SIGTERM, &newAction, NULL);
#else
	signal(SIGINT, quitAll);
#ifdef SIGQUIT
	signal(SIGQUIT, quitAll);
#endif
	signal(SIGTERM, quitAll);
#endif

	// Open the daemon index in read-write mode 
	bool wasObsoleteFormat = false;
	if (ModuleFactory::openOrCreateIndex(settings.m_defaultBackend, settings.m_daemonIndexLocation, wasObsoleteFormat, false) == false)
	{
		cerr << "Couldn't open index " << settings.m_daemonIndexLocation << endl;
		return EXIT_FAILURE;
	}
	if (wasObsoleteFormat == true)
	{
		resetHistory = resetLabels = true;
	}

	// Do the same for the history database
	PinotSettings::checkHistoryDatabase();
	string historyDatabase(settings.getHistoryDatabaseName());
	if ((historyDatabase.empty() == true) ||
		(ActionQueue::create(historyDatabase) == false) ||
		(CrawlHistory::create(historyDatabase) == false) ||
		(MetaDataBackup::create(historyDatabase) == false) ||
		(QueryHistory::create(historyDatabase) == false) ||
		(ViewHistory::create(historyDatabase) == false))
	{
		cerr << "Couldn't create history database " << historyDatabase << endl;
		return EXIT_FAILURE;
	}
	else
	{
		ActionQueue actionQueue(historyDatabase, Glib::get_application_name());
		QueryHistory queryHistory(historyDatabase);
		ViewHistory viewHistory(historyDatabase);
		time_t timeNow = time(NULL);
		unsigned int actionsCount = actionQueue.getItemsCount(ActionQueue::INDEX);

		// Don't expire actions left from last time
		actionsCount += actionQueue.getItemsCount(ActionQueue::UNINDEX);
		cout << actionsCount << " actions left" << endl;

		// Expire the rest
		queryHistory.expireItems(timeNow);
		viewHistory.expireItems(timeNow);
	}

	atexit(closeAll);

#ifdef HAVE_LINUX_SCHED_H
	// Set the scheduling policy
	struct sched_param schedParam;
	if (sched_getparam(0, &schedParam) == -1)
	{
		cerr << "Couldn't get current scheduling policy" << endl;
	}
	else if (sched_setscheduler(0, SCHED_IDLE, &schedParam) == -1)
	{
		cerr << "Couldn't set scheduling policy" << endl;
	}
#else
	// Change the daemon's priority
	if (setpriority(PRIO_PROCESS, 0, priority) == -1)
	{
		cerr << "Couldn't set scheduling priority to " << priority << endl;
	}
#endif

	GError *pError = NULL;
	DBusServletThread::m_pBus = dbus_g_bus_get(DBUS_BUS_SESSION, &pError);
	if (DBusServletThread::m_pBus == NULL)
	{
		if (pError != NULL)
		{
			cerr << "Couldn't open bus connection: " << pError->message << endl;
			if (pError->message != NULL)
			{
				cerr << "Error is " << pError->message << endl;
			}
			g_error_free(pError);
		}

		return EXIT_FAILURE;
	}

	DBusConnection *pConnection = dbus_g_connection_get_connection(DBusServletThread::m_pBus);
	if (pConnection == NULL)
	{
		cerr << "Couldn't get connection" << endl;
		return EXIT_FAILURE;
	}

	DBusError error;
	DaemonState server;
	IndexInterface *pIndex = NULL;

	dbus_error_init(&error);
	dbus_connection_set_exit_on_disconnect(pConnection, FALSE);
	dbus_connection_setup_with_g_main(pConnection, NULL);

	if (dbus_connection_register_object_path(pConnection, PINOT_DBUS_OBJECT_PATH,
		&g_callVTable, &server) == TRUE)
	{
		// Request to be identified by this name
		// FIXME: flags are currently broken ?
		dbus_bus_request_name(pConnection, PINOT_DBUS_SERVICE_NAME, 0, &error);
		if (dbus_error_is_set(&error) == FALSE)
		{
			// See power management signals
			dbus_bus_add_match(pConnection,
				"type='signal',interface='org.freedesktop.PowerManagement'", &error);
			dbus_bus_add_match(pConnection,
				"type='signal',interface='org.gnome.PowerManager'", &error);

			dbus_connection_add_filter(pConnection,
				(DBusHandleMessageFunction)filterHandler, &server, NULL);
		}
		else
		{
			cerr << "Couldn't obtain name " << PINOT_DBUS_SERVICE_NAME << endl;
			if (error.message != NULL)
			{
				cerr << "Error is " << error.message << endl;
			}
		}

		try
		{
			set<string> labels;
			bool gotLabels = false;
			bool onBattery = false;

			pIndex = settings.getIndex(settings.m_daemonIndexLocation);
			if (pIndex != NULL)
			{
				string indexVersion(pIndex->getMetadata("version"));

				gotLabels = pIndex->getLabels(labels);

				// What version is the index at ?
				if (indexVersion.empty() == true)
				{
					indexVersion = "0.0";
				}
				if (ignoreVersion == true)
				{
					// Better reset labels, they may have been lost too
					resetLabels = true;
				}
				else if (indexVersion < PINOT_INDEX_MIN_VERSION)
				{
					cout << "Upgrading index from version " << indexVersion << " to " << VERSION << endl;

					reindex = true;
				}
				if (reindex == true)
				{
					// Reset the index so that all documents are reindexed
					pIndex->reset();
					DBusServletThread::flushIndexAndSignal(pIndex);

					cout << "Reset index" << endl;

					resetHistory = resetLabels = true;
				}

				pIndex->setMetadata("version", VERSION);
				pIndex->setMetadata("dbus-status", "Running");
			}

			if (resetHistory == true)
			{
				CrawlHistory history(historyDatabase);
				map<unsigned int, string> sources;

				// Reset the history
				history.getSources(sources);
				for (std::map<unsigned int, string>::iterator sourceIter = sources.begin();
					sourceIter != sources.end(); ++sourceIter)
				{
					history.deleteItems(sourceIter->first);
					history.deleteSource(sourceIter->first);
				}

				cout << "Reset crawler history" << endl;
			}

			if ((resetLabels == true) &&
				(pIndex != NULL))
			{
				// Re-apply the labels list
				if (gotLabels == false)
				{
					// If this is an upgrade from a version < 0.80, the labels list
					// needs to be pulled from the configuration file
					pIndex->setLabels(settings.m_labels, true);

					cout << "Set labels as per the configuration file" << endl;
				}
				else
				{
					pIndex->setLabels(labels, true);
				}
			}

			// Connect to the quit signal
			server.getQuitSignal().connect(sigc::ptr_fun(&quitAll));

			// Connect to threads' finished signal
			server.connect();

			// Try and get the battery state
			gboolean result = FALSE;
			if ((getBatteryState("org.freedesktop.PowerManagement",
				"/org/freedesktop/PowerManagement", "GetOnBattery", result) == true) ||
				(getBatteryState("org.freedesktop.PowerManagement",
				"/org/freedesktop/PowerManagement", "GetBatteryState", result) == true))
			{
				if (result == TRUE)
				{
					onBattery = true;
				}
			}
			else if (getBatteryState("org.gnome.PowerManager",
				"/org/gnome/PowerManager", "GetOnAc", result) == true)
			{
				if (result == FALSE)
				{
					onBattery = true;
				}
			}
			if (onBattery == true)
			{
				// We are on battery
				server.set_flag(DaemonState::ON_BATTERY);
				server.stop_crawling();

				cout << "System is on battery" << endl;
			}

			server.start(reindex);

			// Run the main loop
			g_refMainLoop->run();

		}
		catch (const Glib::Exception &e)
		{
			cerr << e.what() << endl;
			return EXIT_FAILURE;
		}
		catch (const char *pMsg)
		{
			cerr << pMsg << endl;
			return EXIT_FAILURE;
		}
		catch (...)
		{
			cerr << "Unknown exception" << endl;
			return EXIT_FAILURE;
		}
	}
	else
	{
		cerr << "Couldn't register object path" << endl;
	}
	dbus_error_free(&error);

	if (pIndex != NULL)
	{
		if (server.is_flag_set(DaemonState::DISCONNECTED) == true)
		{
			pIndex->setMetadata("dbus-status", "Disconnected");
		}
		else if (server.is_flag_set(DaemonState::STOPPED) == true)
		{
			pIndex->setMetadata("dbus-status", "Stopped");
		}
		else
		{
			pIndex->setMetadata("dbus-status", "");
		}
		delete pIndex;
	}

	// Stop everything
	server.disconnect();
	server.stop_threads();

	return EXIT_SUCCESS;
}