#include<bits/stdc++.h>
#define maxn 500000
#define ll long long
using namespace std;
char c[maxn];
ll n,cnt,ans,a[maxn],b[maxn],ci,pos[maxn];
set <pair<ll,ll> > s;
int main(){
	scanf("%s",c + 1);
	n = strlen(c + 1);
	for(ll i = 1; i <= n; i++)
		if(c[i] == '?')
			scanf("%lld %lld",&a[i],&b[i]);
	for(ll i = 1; i <= n; i++)
	{
		if(c[i] == '?')
		{
			--cnt;
			ans += b[i];
			s.insert(make_pair(a[i] - b[i],i));
			if(cnt < 0)
			{
				if(s.empty())
				{
					cout << -1;
					return 0;
				}
				cnt += 2;
				ans += (*s.begin()).first;
				pos[(*s.begin()).second] = 1;
				s.erase(s.begin());
			}
		}
		else if(c[i] == '(') ++cnt;
		else
		{
			--cnt;
			if(cnt < 0)
			{
				if(s.empty())
				{
					cout << -1;
					return 0;
				}
				cnt += 2;
				ans += (*s.begin()).first;
				pos[(*s.begin()).second] = 1;
				s.erase(s.begin());
			}
		}
	}
	if(cnt)
	{
		cout << -1;
		return 0;
	}
	cout << ans << endl;
	for(ll i = 1; i <= n; i++)
		if(c[i] != '?') printf("%c",c[i]);
		else if(pos[i]) printf("(");
		else printf(")");
}

#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <utility>

using namespace std;

int get_cur_sum ( char* buf, int num )
{
	int sum = 0;
	for ( int i = 0; i < num; i++ )
	  {
		if ( buf[i] == '(' )
			sum++;
		else if ( buf[i] == ')' )
			sum--;
	  }
	return sum;
}

int main ()
{
	char* buf = new char[50001];
	scanf ( "%s", buf );
	char* cur_pos = buf;
	map<int, pair<int, int> > in_cost; // initial cost
	int num_ask = 0, sum_init = 0;
	int len;
	bool debug = false;
	for ( len = 0; cur_pos[len] != 0; len++ )
	  {
		if ( cur_pos[len] == '?' )
		  {
			num_ask++;
			int oc = 0, cc = 0;
			cin >> oc >> cc;
			if ( cc == 100 )
				debug = false;
			pair<int, int> p ( oc, cc );
			in_cost[len] = p;
		  }
		else if ( cur_pos[len] == '(' )
			sum_init++;
		else if ( cur_pos[len] == ')' )
			sum_init--;
	  }
	if ( sum_init > num_ask || - sum_init > num_ask )
	  {
		cout << -1 << endl;
		return 0;
	  }
	map<int, vector<int> > olc, clc; // open lowest cost, close lowest cost
	map<int, pair<int, int> >::iterator it;
	long long int tot_c = 0;
	for ( it = in_cost.begin(); it != in_cost.end(); it++ )
	  {
		int oc = it->second.first, cc = it->second.second;
		int i = it->first;
		//map<int, pair<int, int> >::iterator temp_it = it;
		//temp_it++;
		//int next_i = len;
		//if ( temp_it != in_cost.end() )
		//next_i = temp_it->first;
		num_ask--;
		//int sum_cur = get_cur_sum ( cur_pos, i );
		//int sum_next = get_cur_sum ( cur_pos, next_i );
		//int sum_min = sum_cur;
		//if ( sum_min > sum_next )
		//sum_min = sum_next;
		//if ( sum_cur == 0 )
		//{
		//clc.clear();
		//}
		if ( i == 0 )
		  {
			cur_pos[i] = '(';
			tot_c += oc;
			//if ( sum_min > 0 )
			//clc[cc-oc+1].push_back ( i );
			//sum_min++;
			sum_init++;
			continue;
		  }
		if ( i == len - 1 )
		  {
			cur_pos[i] = ')';
			tot_c += cc;
			//sum_min--;
			sum_init--;
			//olc[oc-cc+1].push_back ( i );
			continue;
		  }
		if ( oc > cc )
		  {
			cur_pos[i] = ')';
			tot_c += cc;
			//sum_min--;
			sum_init--;
			olc[oc-cc+1].push_back ( i );
		  }
		else
		  {
			cur_pos[i] = '(';
			tot_c += oc;
			//if ( sum_min > 0 )
			clc[cc-oc+1].push_back ( i );
			//sum_min++;
			sum_init++;
		  }
		/*map<int, vector<int> >::iterator it_in;
		vector<int>::reverse_iterator it_in2;
		while ( sum_min < 0 )
		  {
			it_in = olc.begin();
			it_in2 = it_in->second.rbegin();
			int i_in = *it_in2;
			int c_in = it_in->first - 1;
			cur_pos[i_in] = '(';
			tot_c += c_in;
			sum_init += 2;
			sum_min += 2;
			it_in->second.erase ( --(it_in2.base()) );
			if ( it_in->second.size ( ) == 0 )
				olc.erase ( it_in );
			clc.clear ( );
		  }
		if ( sum_init > num_ask )
		  {
			if ( i != len - 1 )
			  {
				it_in = clc.begin();
				it_in2 = it_in->second.rbegin();
			  }
			else
			  {
				bool rflag = true;
				for ( it_in = clc.begin(); it_in != clc.end(); it_in++ )
				  {
					for ( it_in2 = it_in->second.rbegin(); it_in2 != it_in->second.rend(); it_in2++ )
					  {
						if ( *it_in2 == i )
						  {
							rflag = false;
							break;
						  }
					  }
					if ( ! rflag )
						break;
				  }
			  }
			int i_in = *it_in2;
			int c_in = it_in->first - 1;
			cur_pos[i_in] = ')';
			tot_c += c_in;
			sum_init -= 2;
			it_in->second.erase ( --(it_in2.base()) );
			if ( it_in->second.size ( ) == 0 )
				clc.erase ( it_in );
			for ( int i_in2 = 1; i_in2 <= i; i_in2++ )
				if ( get_cur_sum ( cur_pos, i_in2 + 1 ) == 0 )
				  {
					for ( it_in = clc.begin(); it_in != clc.end(); )
					  {
						for ( it_in2 = it_in->second.rbegin(); it_in2 != it_in->second.rend();  )
						  {
							if ( *it_in2 <= i_in2 + 1 )
							  {
								it_in->second.erase ( --(it_in2.base()) );
								it_in2 = it_in->second.rbegin();
							  }
							else
							  {
								it_in2++;
							  }
						  }
						if ( it_in->second.size ( ) == 0 )
						  {
							clc.erase ( it_in );
							it_in = clc.begin();
						  }
						else
						  {
							it_in++;
						  }
					  }
				  }
		  }*/
	  }
	if ( sum_init > 0 )
	  {
		for ( int i = 0; sum_init != 0; i++ )
		  {
			map<int, vector<int> >::iterator it_in = clc.begin();
			vector<int>::reverse_iterator it_in2 = it_in->second.rbegin();
			int i_in = *it_in2;
			int c_in = it_in->first - 1;
			cur_pos[i_in] = ')';
			tot_c += c_in;
			sum_init -= 2;
			it_in->second.erase ( --(it_in2.base()) );
			if ( it_in->second.size ( ) == 0 )
				clc.erase ( it_in );
			olc[1-c_in].push_back ( i_in );
		  }
	  }
	else if ( sum_init < 0 )
	  {
		for ( int i = 0; sum_init != 0; i++ )
		  {
			map<int, vector<int> >::iterator it_in = olc.begin();
			vector<int>::iterator it_in2 = it_in->second.begin();
			int i_in = *it_in2;
			int c_in = it_in->first - 1;
			cur_pos[i_in] = '(';
			tot_c += c_in;
			sum_init += 2;
			it_in->second.erase ( it_in2 );
			if ( it_in->second.size ( ) == 0 )
				olc.erase ( it_in );
			clc[1-c_in].push_back ( i_in );
		  }
	  }
	int sum_cur = 0;
	for ( int i = 0; i < len; i++ )
	  {
		if ( cur_pos[i] == '(' )
			sum_cur++;
		else
			sum_cur--;
		if ( sum_cur == -1 )
		  {
			map<int, vector<int> >::iterator it_in;
			vector<int>::iterator it_in2;
			bool sflag = false;
			for ( it_in = olc.begin(); it_in != olc.end(); it_in++ )
			  {
				for ( it_in2 = it_in->second.begin(); it_in2 != it_in->second.end();  it_in2++ )
				  {
					if ( *it_in2 <= i )
					  {
						cur_pos[*it_in2] = '(';
						sflag = true;
						sum_cur += 2;
						tot_c += it_in->first - 1;
						if ( debug )
							cout << i << 1 << endl;
						it_in->second.erase ( it_in2 );
						if ( debug )
							cout << i << 2 << endl;
						break;
					  }
				  }
				if ( it_in->second.size ( ) == 0 )
				  {
					if ( debug )
						cout << i << 3 << endl;
					olc.erase ( it_in );
					if ( debug )
						cout << i << 4 << endl;
				  }
				if ( sflag )
					break;
			  }
			if ( sflag == false )
			  {
				cout << -1 << endl;
				return 0;
			  }
			sflag = false;
			if ( debug )
				cout << i << 5 << endl;
			vector<int>::reverse_iterator it_in2r;
			for ( it_in = clc.begin(); it_in != clc.end(); it_in++ )
			  {
				for ( it_in2r = it_in->second.rbegin(); it_in2r != it_in->second.rend(); it_in2r++ )
				  {
					if ( *it_in2r > i )
					  {
						cur_pos[*it_in2r] = ')';
						sflag = true;
						tot_c += it_in->first - 1;
						olc[2-it_in->first].push_back ( *it_in2r );
						if ( debug )
							cout << i << 6 << endl;
						it_in->second.erase ( --(it_in2r.base()) );
						it_in2r = it_in->second.rbegin();
						if ( debug )
							cout << i << 7 << endl;
						break;
						if ( it_in->second.size ( ) == 0 )
						  {
							if ( debug )
								cout << i << 8 << endl;
							olc.erase ( it_in );
							it_in = clc.begin();
							if ( debug )
								cout << i << 9 << endl;
						  }
					  }
				  }
				if ( sflag )
					break;
			  }
			if ( debug )
				cout << i << 1 << endl;
			if ( sflag == false )
			  {
				cout << -1 << endl;
				return 0;
			  }
		  }
		if ( debug )
			cout << i << 0 << endl;
	  }
	cout << tot_c << endl;
	cout << buf << endl;
	return 0;
}

This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.


/*
Anton Gulikov
*/
#include <iostream>
#include <fstream>
#include <stack>
#include <cstdlib>
#include <cmath>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cassert>
#include <stdio.h>
#include <queue>

#define mp make_pair
#define pb push_back
#define foru(i,n) for(int i = 0; i < n; i++)
#define ford(i,n) for(int i = n - 1; i >= 0; i++)
#define forab(i,l,r) for(int i = l; i <= r; i++)
#define forabd(i,r,l) for(inr i = r; i >= l; i--)
#define sqr(x) ((x) * (x))

const long long base = 1000000000 + 7;

using namespace std;

typedef pair <int,int> pii;
#define prev sdeigijodfgijs
#define X first
#define Y second

char area[55][55];

int area2[55][55];
int used[55][55];
pii prev[55][55];

int go[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int leng[55*55];
int ccnt[55*55];

void solve(){

   int n,m,k;
   cin >> n >> m >> k;
   int si = -1, sj = -1, ti = -1, tj = -1;
   for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
      {
         cin >> area[i][j];
         if (area[i][j] == 'S') {si = i; sj = j;}
         if (area[i][j] == 'T') {ti = i; tj = j;}
         area2[i][j] = (int)area[i][j] - 'a';
         if (area[i][j] == 'S') area2[i][j] = -2;
         if (area[i][j] == 'T') area2[i][j] = -1;
      }
   assert(si != -1 && ti != -1);
   int F = 1;
   for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
         used[i][j] = 0;
   string res = "";
   swap(si,ti);
   swap(sj,tj);
   int len = (int)1e9;
   for (int a = 0; a < 26; a++)
      for (int b = a+(int)(k>1); b < 26; b++)
         for (int c = b+(int)(k>2); c < 26; c++)
            for (int d = c+(int)(k>3); d < 26; d++)
            {

              int ch[4] = {a,b,c,d};
              for (int i = k; i < 4; i++) ch[i] = ch[k-1];
            //  ch[0] = 0; ch[1] = 1; ch[2] = 1; ch[3] = 1;
              F++;
              priority_queue<pair <int, pair <int, pair< int, pair <int, int> > > >  > q;
              q.push(mp(0,mp(0,mp(0,mp(si,sj)))));
              used[si][sj] = F;
              int poss = (1<<ch[0]) | (1<<ch[1]) | (1<<ch[2]) | (1<<ch[3]);
              while (!q.empty())
              {
                 pair <int, pair <int, pair < int, pair <int, int> > > > u = q.top();
             //    cout << u.X << " " << u.Y.X << " " << u.Y.Y.X << " " << u.Y.Y.Y << endl;
                 q.pop();
                 if (leng[-u.X] != F){
                 	leng[-u.X] = F;
                 	ccnt[-u.X + 1] = 0;
                 }
                 pair<int, pii> goal[4];
                 int cnt = 0;

                 for (int i = 0; i < 4; i++)
                 {
                    pii to = mp(u.Y.Y.Y.X + go[i][0], u.Y.Y.Y.Y + go[i][1]);
                    if (to.X >= 0 && to.X < n && to.Y >= 0 && to.Y < m && used[to.X][to.Y] != F
                        && ( area2[to.X][to.Y] == -2 || (poss & (1<<(area2[to.X][to.Y]))) ) ) goal[cnt++] = mp(area2[to.X][to.Y],to);
                 }
                 for (int i = 0; i < cnt; i++)
                 {
                 	if (used[goal[i].Y.X][goal[i].Y.Y] == F) continue;
                    used[goal[i].Y.X][goal[i].Y.Y] = F;
                    prev[goal[i].Y.X][goal[i].Y.Y] = u.Y.Y.Y;
                    ccnt[-u.X+1]++;
                    q.push(mp(u.X - 1, mp(-goal[i].X,mp(-ccnt[-u.X+1],mp(goal[i].Y.X,goal[i].Y.Y)))));
                 }
              }
              //return;

              if (used[ti][tj] != F) continue;
              string ans = "";
              pii c = prev[ti][tj];
              while (1)
              {
                 if (c == mp(si, sj)) break;
                 ans.pb(area[c.X][c.Y]);
                 c = prev[c.X][c.Y];
              }
           //   reverse(ans.begin(),ans.end());
              if (len > (int)ans.size())
              {
                 len = ans.size();
                 res = ans;
              }
              else if (len == (int)ans.size() && ans < res) res = ans;
            }
  if (len < n*m*2) cout << res << endl;
  else cout << -1 << endl;

}

int main(){
	ios_base :: sync_with_stdio(false);
	int test = 1;
	while (test--){
		solve();
	}
	return 0;
}

#ifndef LOCAL_BOBER
#pragma comment(linker, "/STACK:134217728")
#endif

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <bitset>
#include <queue>
#include <stack>
#include <sstream>
#include <cstring>
#include <numeric>
#include <ctime>

#define re return
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int) (x).size())
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rrep(i, n) for (int i = (n) - 1; i >= 0; i--)
#define y0 y32479
#define y1 y95874
#define fill(x, y) memset(x, y, sizeof(x))
#define sqr(x) ((x) * (x))
#define prev prev239
#define next next239
#define hash hash239
#define rank rank239
#define sqrt(x) sqrt(abs(x))

using namespace std;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<string> vs;
typedef long long ll;
typedef double D;
typedef long double LD;

template<class T> T abs(T x) {return x > 0 ? x : -x;}

int n;
int m;

int matr[50][50];

bool cmp(string a, string b) {
    if (sz(a) != sz(b))
        re sz(a) < sz(b);
    re a < b;
}

int x1, y1, x2, y2;
int d[50][50];
queue<ii> q;

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int mask;

int good(int x, int y) {
    re x >= 0 && x < n && y >= 0 && y < m && (mp(x1, y1) == mp(x, y) || mp(x2, y2) == mp(x, y) || ((1 << matr[x][y]) & mask) != 0);
}

void parse(ii o) {
    int x = o.fi;
    int y = o.se;
    int dist = d[x][y];
    rep(i, 4) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (good(nx, ny) && d[nx][ny] == -1) {
            d[nx][ny] = dist + 1;
            q.push(mp(nx, ny));
        }
    }
}

string getans(int mask) {
    ::mask = mask;
    fill(d, -1);
    q.push(mp(x2, y2));
    d[x2][y2] = 0;
    while (!q.empty()) {
        parse(q.front());
        q.pop();
    }
    if (d[x1][y1] == -1)
        re "-";
    int cx = x1, cy = y1;
    string ans = "";
    vii v;
    v.pb(mp(x1, y1));
    vii tmp;
    tmp.reserve(1000);
    while (1) {
        int dist = d[v[0].fi][v[0].se];
        if (dist == 1)
            break;
        char bc = 'z' + 1;
        rep(o, sz(v))
        rep(i, 4) {
            int nx = v[o].fi + dx[i];
            int ny = v[o].se + dy[i];
            if (good(nx, ny) && d[nx][ny] == dist - 1) {
                if (matr[nx][ny] + 'a' < bc) {
                    bc = matr[nx][ny] + 'a';
                }
            }
        }
        tmp.clear();
        rep(o, sz(v))
        rep(i, 4) {
            int nx = v[o].fi + dx[i];
            int ny = v[o].se + dy[i];
            if (good(nx, ny) && d[nx][ny] == dist - 1) {
                if (matr[nx][ny] + 'a' == bc) {
                    tmp.pb(mp(nx, ny));
                }
            }
        }
        sort(all(tmp));
        tmp.resize(unique(all(tmp)) - tmp.begin());
        ans += bc;
        v = tmp;
    }

    re ans;
}

int main() {
#ifdef LOCAL_BOBER
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
#endif

    int k;
    scanf("%d%d%d", &n, &m, &k);
    rep(i, n) {
        char s[1000];
        scanf("%s", s);
        rep(j, m) {
            matr[i][j] = s[j] - 'a';
            if (s[j] == 'S') {
                x1 = i;
                y1 = j;
            }
            if (s[j] == 'T') {
                x2 = i;
                y2 = j;
            }
        }
    }

    vi v;
    v.reserve(20000);
    rep(i, (1 << 26)) {
        if (__builtin_popcount(i) <= k)
            v.pb(i);
    }
    string res = "-";
    rep(i, sz(v)) {
        string ans = getans(v[i]);
        if (ans != "-")
            if (res == "-" || cmp(ans, res))
                res = ans;
    }
    if (res == "-")
        cout << -1 << endl;
    else
        cout << res << endl;

    re 0;
}

You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.The track's map is represented by a rectangle n×m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once — at the very beginning, and T must be visited exactly once — at the very end.Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.

[{'input': '5 3 2\nSba\nccc\naac\nccc\nabT\n', 'output': ['bcccc\n']}, {'input': '3 4 1\nSxyy\nyxxx\nyyyT\n', 'output': ['xxxx\n']}, {'input': '1 3 3\nTyS\n', 'output': ['y\n']}, {'input': '1 4 1\nSxyT\n', 'output': ['-1\n']}, {'input': '1 3 3\nSaT\n', 'output': ['a\n']}, {'input': '3 4 1\nSbbT\naaaa\nabba\n', 'output': ['bb\n']}, {'input': '3 5 2\nSbcaT\nacbab\nacccb\n', 'output': ['aacccaa\n']}, {'input': '3 4 1\nSbbb\naaaT\nabbc\n', 'output': ['aaa\n']}, {'input': '3 4 2\nSbbb\naabT\nabbc\n', 'output': ['aab\n']}, {'input': '1 2 1\nST\n', 'output': ['\n']}, {'input': '4 5 3\nabaaa\nbabaT\nSabba\naaaaa\n', 'output': ['aaba\n']}, {'input': '6 6 3\npkhipk\nmlfmak\naqmbae\ndlbfSj\ndpbjcr\naTbqbm\n', 'output': ['cbqb\n']}, {'input': '1 20 3\nacbccbbddbffScTadffd\n', 'output': ['c\n']}, {'input': '1 30 2\nbmjcfldkloleiqqiTnmdjpaSckkijf\n', 'output': ['-1\n']}, {'input': '1 40 1\nfaSfgfTcfadcdfagfbccbffbeaaebagbfcfcgdfd\n', 'output': ['-1\n']}, {'input': '1 50 3\nSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaTaaaaaaaaaaa\n', 'output': ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n']}, {'input': '5 10 4\naaaaaaaaaa\naaaaaTaaaa\naaaaaaaSaa\naaaaaaaaaa\naaaaaaaaaa\n', 'output': ['aa\n']}, {'input': '5 3 4\naaT\nacc\nbbb\nbbc\ncSb\n', 'output': ['bbbc\n']}, {'input': '5 5 1\ncaTbc\ndccac\ndacda\naacaS\ncdcab\n', 'output': ['-1\n']}, {'input': '10 8 2\nbdcdcbfa\ndecffcce\ndTffdacb\neeedcdbb\nfdbbbcba\nddabfcda\nabdbSeed\nbdcdcffa\ncadbaffa\nfcccddad\n', 'output': ['bbbbee\n']}, {'input': '20 10 3\nebebccacdb\neeebccddeT\neadebecaac\nadeeeaccbc\nbaccccdaed\ndeabceabba\ndadbecbaaa\neacbbcedcb\naeeScdbbab\nbabaecaead\nbacdbebeae\naacbadbeec\nacddceecca\nacaeaebaba\ncdddeaaeae\neabddadade\nddddaeaeed\nbccbaacadd\ndccccbabdc\necdaebeccc\n', 'output': ['bbbcccaccaac\n']}, {'input': '15 10 4\nsejwprqjku\npnjsiopxft\nrsplgvwixq\nendglkchxl\nftihbbexgh\nsxtxbbavge\njcdkusfnmr\nskgsqvflia\nkcxmcxjpae\namaiwcfile\nnjgjSunmwd\nldxvahgreu\necmrajbjuT\nnaioqigols\npbwrmxkltj\n', 'output': ['aajbju\n']}, {'input': '15 3 4\nllv\nttT\nhbo\nogc\nkfe\ngli\nfbx\nkfp\nspm\ncxc\nndw\nSoa\npfh\nedr\nxmv\n', 'output': ['-1\n']}, {'input': '15 15 3\ncbbdccabdcbacbd\nbcabdcacadacdbc\ncbcddbbcdbddcad\nddcabdbbdcabbdc\naabadcccTcabdbb\ncbacaaacaabdbbd\ndbdcbSdabaadbdb\ndbbaddcdddaadbb\nbbddcdcbaccbbaa\nadadadbdbbddccc\ncddbbdaddcbbdcc\nbbaadcdbbcaacca\nadbdcdbbcbddbcd\ncdadbcccddcdbda\ncbcdaabdcabccbc\n', 'output': ['aaca\n']}, {'input': '20 20 2\nddadfcdeTaeccbedeaec\nacafdfdeaffdeabdcefe\nabbcbefcdbbbcdebafef\nfdafdcccbcdeeaedeffc\ndfdaabdefdafabaabcef\nfebdcabacaaaabfacbbe\nabfcaacadfdbfdbaaefd\ndacceeccddccaccdbbce\ncacebecabedbddfbfdad\ndacbfcabbebfddcedffd\ncfcdfacfadcfbcebebaa\nddfbebafaccbebeefbac\nebfaebacbbebdfcbcbea\ndfbaebcfccacfeaccaad\nedeedeceebcbfdbcdbbe\nafaacccfbdecebfdabed\nddbdcedacedadeccaeec\necbSeacbdcccbcedafef\ncfdbeeffbeeafccfdddb\ncefdbdfbabccfdaaadbf\n', 'output': ['-1\n']}, {'input': '10 10 2\nbaaaaaaaaa\nbffacffffa\nbggaccggga\nbbbSccchha\nbdddddccia\nbjddccccca\nbkkdddTaaa\nblllddblla\nbmmmmdbmma\nbbbbbbbbbb\n', 'output': ['ccccc\n']}, {'input': '10 20 3\nbaaaaaaaaaaaaaaaaaaa\nbfffffffacfffffffffa\nbgggggggaccgggggggga\nbbbbbbbbSccchhhhhhha\nbiiiiidddddcciiiiiia\nbjjjjjjddcccccjjjjja\nbkkkkkkkdddTaaaaaaaa\nbllllllllddbllllllla\nbmmmmmmmmmdbmmmmmmma\nbbbbbbbbbbbbbbbbbbbb\n', 'output': ['ccccc\n']}, {'input': '20 10 4\nbaaaaaaaaa\nbffacffffa\nbggaccggga\nbhhaccchha\nbiiaccccia\nbjjaccccca\nbkkakkkkka\nbllallllla\nbbbSmmmmma\nbnnnnnnnna\nbooooooooa\nbpppppTaaa\nbqqqqqbqqa\nbrrrrrbrra\nbdddddbssa\nbtddddbtta\nbuudddbuua\nbvvvddbvva\nbwwwwdbwwa\nbbbbbbbbbb\n', 'output': ['mmmno\n']}, {'input': '20 20 2\nbaaaaaaaaaaaaaaaaaaa\nbfffffffacfffffffffa\nbgggggggaccgggggggga\nbhhhhhhhaccchhhhhhha\nbiiiiiiiacccciiiiiia\nbjjjjjjjacccccjjjjja\nbkkkkkkkacccccckkkka\nblllllllacccccccllla\nbbbbbbbbSccccccccmma\nbddddddddddcccccccna\nbodddddddcccccccccca\nbppddddddddTaaaaaaaa\nbqqqdddddddbqqqqqqqa\nbrrrrddddddbrrrrrrra\nbsssssdddddbsssssssa\nbttttttddddbttttttta\nbuuuuuuudddbuuuuuuua\nbvvvvvvvvddbvvvvvvva\nbwwwwwwwwwdbwwwwwwwa\nbbbbbbbbbbbbbbbbbbbb\n', 'output': ['ccccc\n']}, {'input': '1 2 4\nST\n', 'output': ['\n']}, {'input': '3 3 1\naaa\naaa\nTSa\n', 'output': ['\n']}, {'input': '2 1 1\nS\nT\n', 'output': ['\n']}, {'input': '1 10 2\nbaaSaaTacb\n', 'output': ['aa\n']}, {'input': '2 1 4\nS\nT\n', 'output': ['\n']}]


#include<cstdio>
#include<iostream>
#include<set>
#include<map>
#include<complex>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n)   REP(i,0,n)
#define ALL(C)     (C).begin(),(C).end()
#define pb push_back
#define mp make_pair

typedef long long ll;
const double eps = 1e-10;
const int N = 2*5000000;
bool isexist[N+1]={false};

ll solve(ll b,ll c){
  ll ret=0;
  ll tmp1=(ll)sqrt(b*b-1),tmp2=(ll)sqrt(b*b-min(b*b,c+1));
  ret=2*(min(b*b-1,c)-(tmp1-tmp2));
  //cout << b <<" " << c <<" " << tmp1 <<" " << tmp2 << endl;
  //if (b==1)ret=0;
  //ll cnt=tmp1-tmp2;
  ll cnt=(ll)floor(sqrt(b*b-1))-(ll)ceil(sqrt(b*b-min(b*b,c+1)));
  //cout << b <<" " << c <<" " << ret <<" " << cnt <<  endl;
  //cout << sqrt(b*b-1) <<" " << sqrt(b*b-min(b*b,c+1)) << endl;
  if (c >= b*b){
    if (!isexist[N-b])ret++;
    isexist[N-b]=true;
  }
  ll l = (ll)ceil(sqrt(b*b-min(b*b,c))),r=(ll)floor(sqrt(b*b-1));
  REP(i,l,r+1){
  //  REP(i,1,cnt+1){
    //cout << isexist[N+-b+(b-i)] <<" " << isexist[N+-b-(b-i)] <<" " << ret << endl;
    // if (!isexist[N+-b+(b-i)])ret++;
    // isexist[N+-b+(b-i)]=true;
    // if (!isexist[N+-b-(b-i)])ret++;
    // isexist[N+-b-(b-i)]=true;
    if (!isexist[N+-b+i])ret++;
    isexist[N+-b+i]=true;
    if (!isexist[N+-b-i])ret++;
    isexist[N+-b-i]=true;
  }
  //cout << "finally " << b <<" "<< c <<" " << ret << endl;
  return ret;
}

main(){
  ll b,c;
  ll ans=0;
  cin>>b>>c;
  rep(i,N+1)isexist[i]=false;
  //isexist[-1+N]=true;
  REP(i,1,b+1){
    ans+=solve(i,c);
  }
  // cout <<"irattional answer " << ans << endl;
  // rep(i,N){
  //   if (isexist[i])ans++;
  //   if (isexist[i])cout<<i-N <<endl;
  // }
  cout << ans << endl;
  //solve(6,21);

  return false;
}

#include <iostream>
#include <ctime>
#include <fstream>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <utility>
#include <cctype>

using namespace std;

#define FORALL(i,a,b) for(int i=(a);i<=(b);++i)
#define FOR(i,n) for(int i=0;i<(n);++i)
#define FORB(i,a,b) for(int i=(a);i>=(b);--i)

typedef long long ll;
typedef long double ld;
typedef complex<ld> vec;

typedef pair<int,int> pii;
typedef map<int,int> mii;

#define pb push_back
#define mp make_pair

#define EPS 1e-9
#define INF 1000000000

int integers(ld a, ld b){
	assert(a >= 0 && b >= 0);
	int x = (int)(ceil(a-EPS)+EPS);
	int y = (int)(floor(b+EPS)+EPS);
	if (y<x) return 0;
	return y-x+1;
}

#define MAXN 10000005
bool good[MAXN];

int main(){
	int N,M;
	cin >> N >> M;

	ll ans = 0;
	vector< pair<ld,ld> > S(2*N);

	ld low,high;
	int b;
	for(b=1;b<=N;++b) {
		low = sqrt(max(0ll,1ll*b*b-M));
		high = sqrt((ld)b*(ld)b-1);
		S[2*b-2] = mp(low-b,high-b);
		S[2*b-1] = mp(-high-b, -low-b);

		int adder = (int)min(1ll*M,1ll*b*b);
		adder -= integers(low,high);

		ans += 2*adder;
	};

	N = S.size();
	FOR(i,N) {
		ld a = S[i].first, b = S[i].second;
		for(int k=(int)(a-1-EPS);k<=(int)(b+1+EPS);++k){
			if (a-EPS<=k&&k<=b+EPS && !good[-k]){
				good[-k] = true;
				++ans;
			}
		}
	}

	cout << ans << endl;
}

A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: x^2+2bx+c=0 where b, c are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1≤b≤n, 1≤c≤m. Help Petya find that number.


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<sstream>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
int cnt,M;
bool arr [ 1000 ];
int pos [ 1000] , num [ 1000 ];
void doAlloc()
{
        int n;
        cin >> n;
        bool found = false;
        //cout << n <<"\n";
        for ( int i = 0 ; i+n <= M ;i++ )
        {
                bool flag = true;
                for ( int j = 0 ; j < n ; j++ ) if ( !arr [i+j] ) flag = false;
                if ( flag )
                {
                        ++cnt;pos [cnt] = i ;cout<<cnt <<"\n";found = true;num [cnt] = n;
                        for ( int j = 0 ; j < n ;j++ ) arr [i+j] = false;
                        break;
                }
        }
        if ( !found ) cout <<"NULL\n";
        //else cout << cnt <<"\n";
        return;
}
void doErase ()
{
        int x;
        cin >> x;
	if ( x > cnt || x <= 0 ) { cout << "ILLEGAL_ERASE_ARGUMENT\n"; return;}
        int t = pos [x];
        if ( x > cnt || t == -1 ) {cout <<"ILLEGAL_ERASE_ARGUMENT\n"; return;}
        bool found = false;
        for ( int  i = 0 ; i < num [x] ;i++ ) if ( arr [i+t] ) found = true;else arr [i+t] = true;
        if ( found ) cout <<"ILLEGAL_ERASE_ARGUMENT\n";
        else pos [x] = num [x] = -1;
        return ;
}
void doFrament ()
{
        int last = 0;
        //for ( int i = 1 ; i <= cnt ; i++ ) if ( pos [i] != -1 ) cout << pos [i] << " " ; cout <<"\n";
        for ( int i = 1 ; i <= cnt ;i++ )
        {
                int t = pos [i] , n = num [i] ,p;
                if ( t == -1 ) continue;
                p = t;
                for ( int j = last ;  j < t ; j++ ) if ( arr [j] ) { p = j ; break;}
                //if ( p == -1 ) { p = t ;}
                int x = t + n -1;
                for ( int j = 0 ; j < n ;j++ ) arr [p+j] = false;
                for ( int j = p+n ; j <= x ;j++ ) arr [j] = true;
                pos [i] = p;
                last = p+n;
        }
        //for ( int i = 1 ; i <= cnt ; i++ ) if ( pos [i] != -1 ) cout << pos [i] << " " ; cout <<"\n";
        return ;
}
int main ()
{
        int T;
        cin >> T >> M;
        memset ( arr , true , sizeof ( arr ) );
        for ( int i = 0 ; i < T ;i++ )
        {
                string command ;
                cin >> command;
                if ( command =="alloc")  doAlloc();
                else if ( command == "erase") doErase();
                else doFrament();
        }
        return 0;
}

There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

[{'input': '6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n', 'output': ['1\n2\nNULL\n3\n']}, {'input': '6 1\ndefragment\nalloc 10\nalloc 1\nerase -1\nerase 1\nerase 1\n', 'output': ['NULL\n1\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '14 100\nalloc 99\nalloc 1\nalloc 1\nerase 2\nalloc 1\nerase 4\nerase 1\nalloc 100\nalloc 1\nalloc 99\ndefragment\nerase 4\nalloc 100\nalloc 99\n', 'output': ['1\n2\nNULL\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\n4\nNULL\nNULL\nNULL\n']}, {'input': '26 25\ndefragment\nerase 1\nerase -1560200883\nalloc 44\ndefragment\nalloc 75\nalloc 22\ndefragment\nerase 4\ndefragment\nalloc 57\nalloc 53\nerase 4\nerase -1639632026\nerase -2121605039\nerase 3\nalloc 51\nalloc 65\ndefragment\nerase 2\nerase 4\nalloc 52\nerase 3\ndefragment\nerase -1842529282\nerase 3\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n1\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '22 9\nerase 1\nalloc 6\nalloc 65\nerase 1\nalloc 87\nerase -1638927047\nalloc 5\nerase 2\nalloc 70\ndefragment\nalloc 20\nalloc 48\nerase -69401977\nalloc 20\ndefragment\nerase 7\ndefragment\nerase 9\nerase 7\nerase 4\ndefragment\nalloc 66\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '12 40\nerase 1\nalloc 21\nalloc 5\nalloc 7\ndefragment\ndefragment\nerase 2\nalloc 83\nerase 4\ndefragment\nalloc 59\ndefragment\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\n2\n3\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '38 18\nalloc 72\nerase 2\nalloc 50\ndefragment\nerase 3\ndefragment\nalloc 43\nalloc 41\ndefragment\ndefragment\nalloc 26\nalloc 46\nalloc 16\nalloc 15\ndefragment\ndefragment\nalloc 95\nerase 7\nerase 7\nerase 5\nerase 2\nerase 9\nerase 7\nalloc 43\ndefragment\nerase 7\ndefragment\nalloc 48\nalloc 77\nerase 10\nerase 11\nalloc 16\nalloc 84\nerase 1\ndefragment\nalloc 86\ndefragment\nerase 13\n', 'output': ['NULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nNULL\n1\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '37 74\nalloc 11\ndefragment\nerase 1\ndefragment\nerase 2\ndefragment\nalloc 90\nerase 3\nerase 2\nerase 3\nerase 1\nerase 1\nalloc 38\nalloc 19\nerase 1\nerase 3\ndefragment\nalloc 93\nerase 5\nerase 4\nalloc 66\nalloc 71\nerase 5\ndefragment\ndefragment\ndefragment\ndefragment\nerase 7\nalloc 47\nerase -95616683\nerase 2\nalloc 28\nalloc 32\nerase 11\nalloc 50\ndefragment\ndefragment\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n4\n5\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '16 49\nerase -751005193\ndefragment\nalloc 37\nalloc 82\nerase 3\nerase 1\nalloc 80\nalloc 51\ndefragment\nalloc 74\nerase 1\nalloc 91\ndefragment\ndefragment\nalloc 98\ndefragment\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '42 98\ndefragment\ndefragment\ndefragment\ndefragment\ndefragment\nalloc 5\nalloc 66\ndefragment\nerase 3\nalloc 53\ndefragment\nerase 4\nerase 2\nalloc 70\nerase 3\ndefragment\ndefragment\nerase 2\nerase 3\nerase -1327931832\nalloc 93\nalloc 64\nerase 7\nerase 6\nerase 3\nalloc 61\nalloc 12\nalloc 65\nerase 2\nalloc 46\nerase 11\nerase 9\nerase 9\nerase 6\nalloc 2\nalloc 78\ndefragment\nerase 13\nerase 6\nerase 10\nalloc 53\nalloc 46\n', 'output': ['1\n2\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n4\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '19 46\nalloc 21\nerase 2\nerase 1\ndefragment\nalloc 4\ndefragment\ndefragment\nalloc 40\nerase 1\ndefragment\ndefragment\nalloc 68\nerase -388966015\nalloc 85\nalloc 53\nerase 4\ndefragment\nalloc 49\nalloc 88\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '44 46\nalloc 28\nalloc 36\ndefragment\nerase -937404236\nalloc 71\ndefragment\nalloc 81\nalloc 51\nerase 3\ndefragment\nalloc 48\nerase 1\ndefragment\nalloc 36\ndefragment\ndefragment\nerase 1\ndefragment\ndefragment\nerase -1173350787\nalloc 94\nerase 5\ndefragment\nerase 9\nalloc 98\nerase 7\ndefragment\nerase 5\nerase 1\ndefragment\nerase 2\ndefragment\nerase 4\ndefragment\nerase 9\nalloc 8\ndefragment\nerase 9\ndefragment\ndefragment\ndefragment\nerase 1\nalloc 70\nerase 9\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n2\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '26 25\nalloc 25\nerase 1\nalloc 24\nerase 2\nalloc 23\nerase 3\nalloc 24\nerase 4\nalloc 24\nerase 5\nalloc 21\nerase 6\nalloc 24\nerase 7\nalloc 25\nerase 8\nalloc 25\nerase 9\nalloc 24\nerase 10\nalloc 25\nerase 11\nalloc 25\nerase 12\nalloc 25\nerase 13\n', 'output': ['1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n']}, {'input': '22 9\nalloc 9\nerase 1\nalloc 9\nerase 2\nalloc 9\nerase 3\nalloc 9\nerase 4\nalloc 9\nerase 5\nalloc 9\nerase 6\nalloc 9\nerase 7\nalloc 9\nerase 8\nalloc 9\nerase 9\nalloc 9\nerase 10\nalloc 9\nerase 11\n', 'output': ['1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n']}, {'input': '7 6\nalloc 1\nalloc 2\nalloc 3\nerase 1\ndefragment\nerase 3\nalloc 4\n', 'output': ['1\n2\n3\n4\n']}, {'input': '3 1\nerase -1\nerase 0\nerase -2147483648\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '7 100\nalloc 100\nerase 2147483647\nerase 1\nalloc 50\nalloc 50\nerase 3\nerase -2147483648\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '12 10\nalloc 6\nalloc 2\nerase 1\nalloc 4\nalloc 2\nerase 3\nalloc 2\nalloc 3\nalloc 1\nalloc 1\nalloc 1\nalloc 1\n', 'output': ['1\n2\n3\n4\n5\nNULL\n6\n7\n8\n9\n']}, {'input': '8 50\nalloc 51\ndefragment\nalloc 100\ndefragment\nerase 1\nalloc 50\ndefragment\nalloc 50\n', 'output': ['NULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n1\nNULL\n']}, {'input': '10 10\nalloc 10\nerase -1\nerase 1\nalloc 5\nerase -1\nalloc 5\nerase 0\nalloc 5\nerase 0\nalloc 5\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '16 10\nalloc 10\ndefragment\ndefragment\ndefragment\nalloc 10\nerase 1\nerase 2\nalloc 6\ndefragment\ndefragment\nalloc 4\ndefragment\ndefragment\nerase 3\ndefragment\nalloc 6\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\n3\nNULL\n']}, {'input': '16 10\nalloc 10\ndefragment\ndefragment\ndefragment\nalloc 10\nerase 1\nerase 2\nalloc 6\ndefragment\ndefragment\nalloc 4\ndefragment\ndefragment\nerase 2\ndefragment\nalloc 6\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\n3\n4\n']}]


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[5010],b[5010],v[5010],n,m,l,r,i,j,d,mid,ans;

void dfs(int x,int y)
{
	v[x]=y;
	for(int i=0;i<n;i++)
		if(abs(a[i]-a[x])+abs(b[i]-b[x])>d)
			if(!v[i]) dfs(i,3-y); else if(v[i]==y) throw 0;
}

int solve(int dis)
{
	int m=0,i; d=dis;
	memset(v,0,sizeof(v));
	for(i=0;i<n;i++)
		if(!v[i]) try{m++; dfs(i,1);}catch(...){return 0;}
	return m;
}

int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	for(i=0;i<n;i++)
		cin>>a[i]>>b[i];
	r=10000;
	while(l<=r)
	{
		mid=(l+r)>>1;
		if(solve(mid)) r=mid-1; else l=mid+1;
	}
	for(i=solve(l),ans=1;i;i--) ans=ans*2%1000000007;
	cout<<l<<endl<<ans<<endl;
	return 0;
}

#include <iostream>
#include <cstring>
#include <cmath>
#define FOR(i, a, n) for (register int i = (a); i < (int)(n); ++i)
using namespace std;
const int MAXN = 5050;
const int MOD = 1000000007;
int n, threshold;
short x[MAXN], y[MAXN], dist[MAXN][MAXN];
int mark[MAXN];
bool dfs(int pos, int color = 0) {
    if (mark[pos] != -1) return mark[pos] == color;
    mark[pos] = color;
    FOR(i, 0, n) if (dist[pos][i] > threshold && !dfs(i, color^1)) return false;
    return true;
}
int count_ways() {
    memset(mark, -1, sizeof mark);
    int res = 1;
    FOR(i, 0, n) if (mark[i] == -1) {
        if (!dfs(i)) return -1;
        res = res*2%MOD;
    }
    return res;
}
int main () {
    ios::sync_with_stdio(false);
    cin >> n;
    FOR(i, 0, n) {
        cin >> x[i] >> y[i];
        FOR(j, 0, i+1) dist[i][j] = dist[j][i] = abs(x[i]-x[j])+abs(y[i]-y[j]);
    }
    int lo = 0, hi = 10000;
    while (lo < hi)
    {
        threshold = (lo+hi)/2;
        if (count_ways() == -1)
            lo = threshold+1;
        else
            hi = threshold;
    }
    threshold = lo;
    cout << threshold << endl;
    cout << count_ways() << endl;
    return 0;
}

In a far away kingdom lives a very greedy king. To defend his land, he built n guard towers. Apart from the towers the kingdom has two armies, each headed by a tyrannical and narcissistic general. The generals can't stand each other, specifically, they will never let soldiers of two armies be present in one tower.During defence operations to manage a guard tower a general has to send part of his army to that tower. Each general asks some fee from the king for managing towers. As they live in a really far away kingdom, each general evaluates his fee in the following weird manner: he finds two remotest (the most distant) towers, where the soldiers of his army are situated and asks for the fee equal to the distance. Each tower is represented by a point on the plane with coordinates (x,y), and the distance between two points with coordinates (x1,y1) and (x2,y2) is determined in this kingdom as |x1-x2|+|y1-y2|.The greedy king was not exactly satisfied with such a requirement from the generals, that's why he only agreed to pay one fee for two generals, equal to the maximum of two demanded fees. However, the king is still green with greed, and among all the ways to arrange towers between armies, he wants to find the cheapest one. Each tower should be occupied by soldiers of exactly one army.He hired you for that. You should find the minimum amount of money that will be enough to pay the fees. And as the king is also very scrupulous, you should also count the number of arrangements that will cost the same amount of money. As their number can be quite large, it is enough for the king to know it as a remainder from dividing by 10^9+7.Two arrangements are distinct if the sets of towers occupied by soldiers of the first general are distinct.


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdlib>

#define pb(x) push_back(x)
#define size(S) S.size()

using namespace std;

const int maxn=20010;
const unsigned INF=0xFFFFFFFF;
int n, m, p;
string ans;
unsigned int g[maxn/2][maxn/32+1];
int f[2][maxn], x[maxn], y[maxn];

inline int F(int a, int b){return (x[a]+y[b])%p;}

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

	int now=0, pre=1, h=n/2;
	for (int i=0; i<n; i++){
		for (int j=0; j<m; j++){
			if (i+j==0) continue;
			int p=-1, q=-1;
			if (i>0) p=f[pre][j]+F(i-1, j);
			if (j>0) q=f[now][j-1]+F(i, j-1);
			if (p>q){
				f[now][j]=p;
				if (i>=h) g[i-h][j/32]&=INF-(1<<(j%32));
			}else{
				f[now][j]=q;
				if (i>=h) g[i-h][j/32]|=1<<(j%32);
			}
		}
		now^=1, pre^=1;
		memset(f[now], 255, sizeof(f[now]));
	}
	cout<<f[pre][m-1]+F(n-1, m-1)<<endl;

	int nx=n-1, ny=m-1;
	while (nx>=h && !(nx==0 && ny==0)){
		if ((g[nx-h][ny/32]&(1<<(ny%32))) && ny==0) break;
		if ((g[nx-h][ny/32]&(1<<(ny%32)))) ny--, ans+='S';
		else nx--, ans+='C';
	}

	now=0; pre=1;
	memset(f, 0, sizeof(f));
	memset(g, 0, sizeof(g));
	for (int i=0; i<h; i++){
		for (int j=0; j<m; j++){
			if (i+j==0) continue;
			int p=-1, q=-1;
			if (i>0) p=f[pre][j]+F(i-1, j);
			if (j>0) q=f[now][j-1]+F(i, j-1);
			if (p>q){
				f[now][j]=p;
				g[i][j/32]&=INF-(1<<(j%32));
			}else{
				f[now][j]=q;
				g[i][j/32]|=1<<(j%32);
			}
		}
		now^=1, pre^=1;
		memset(f[now], 255, sizeof(f[now]));
	}

	while (!(nx==0 && ny==0)){
		if ((g[nx][ny/32]&(1<<(ny%32)))) ny--, ans+='S';
		else nx--, ans+='C';
	}

	reverse(ans.begin(), ans.end());
	cout<<ans<<endl;
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

#define clr(x) memset((x), 0, sizeof(x))
#define pb push_back
#define mp make_pair
#define sz size()
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define ford(i, n) for(int i=(n)-1; i>=0; i--)
#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)

template <class _T> inline _T sqr(const _T& x) { return x * x; }
template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); }

typedef long double ld;

// Constants
const ld PI = 3.1415926535897932384626433832795;
const ld EPS = 1e-11;

// Types
typedef long long i64;
typedef set < int > SI;
typedef vector < int > VI;
typedef map < string, int > MSI;
typedef pair < int, int > PII;

const int MID = 10001;

int m;
int l1, l2, p;
int a1[20240];
int a2[20240];
int d[2][20240];
unsigned int pa[10020][20240 >> 5];
char ans[40240];

inline int f(int x, int y)
{
	int r = a1[x] + a2[y];
	if (r >= p) r -= p;
	return r;
}

void solve()
{
	d[0][0] = f(0, 0);
	clr(pa);
	forn(j, l2-1)
	{
		d[0][j+1] = d[0][j] + f(0, j+1);
	}
	forn(i, l1 - 1)
	{
		int i1 = i & 1;
		int in = i1 ^ 1;
		memset(d[in], 0, sizeof(d[in]));
		d[in][0] = d[i1][0] + f(i + 1, 0);
		if (i+1 <= MID) pa[i+1][0 >> 5] |= 1 << 0;
		forn(j, l2 - 1)
		{
			int t = f(i+1, j+1);
//			if (d[in][j+1] < d[in][j] + t)
//			{
				d[in][j+1] = d[in][j] + t;
//			}
			if (d[in][j+1] < d[i1][j+1] + t)
			{
				d[in][j+1] = d[i1][j+1] + t;
				if (i+1 <= MID) pa[i+1][(j+1) >> 5] |= (1 << (j+1));
			}
		}
	}
}

void solve2()
{
	d[0][0] = f(0, 0);
	clr(pa);
	forn(j, l2-1)
	{
		d[0][j+1] = d[0][j] + f(0, j+1);
	}
	forn(i, l1 - 1)
	{
		int i1 = i & 1;
		int in = i1 ^ 1;
		memset(d[in], 0, sizeof(d[in]));
		d[in][0] = d[i1][0] + f(i + 1, 0);
		if (i+1 >= MID) pa[i+1-MID][0 >> 5] |= 1 << 0;
		forn(j, l2 - 1)
		{
			int t = f(i+1, j+1);
//			if (d[in][j+1] < d[in][j] + t)
//			{
				d[in][j+1] = d[in][j] + t;
//			}
			if (d[in][j+1] < d[i1][j+1] + t)
			{
				d[in][j+1] = d[i1][j+1] + t;
				if (i+1 >= MID) pa[i+1-MID][(j+1) >> 5] |= (1 << (j+1));
			}
		}
	}
}

int main()
{
#ifdef ROOM_311
	freopen("input.txt", "rt", stdin);
	time_t et_0 = clock();
#else
#endif
	cout << setiosflags(ios::fixed) << setprecision(10);

	scanf("%d%d%d", &l1, &l2, &p);
	forn(i, l1)
	{
		scanf("%d", &a1[i]);
		if (a1[i] > 20000) for(;;);
		a1[i] %= p;
	}
	forn(i, l2)
	{
		scanf("%d", &a2[i]);
		if (a2[i] > 20000) for(;;);
		a2[i] %= p;
	}
/*	forn(i, l1)
	{
		forn(j, l2)
		{
			cerr << f(i, j) << " ";
		}
		cerr << endl;
	}*/
	clr(d);
	solve2();
	int xx = d[(l1 & 1) ^ 1][l2 - 1];
	printf("%d\n", d[(l1 & 1) ^ 1][l2 - 1]);

	m = 0;
	int x = l1 - 1;
	int y = l2 - 1;
	bool ff = false;
	while (x || y)
	{
		if (x <= MID && !ff)
		{
			solve();
			ff = true;
		}
		int r = x <= MID ? ((pa[x][y >> 5] >> y) & 1) : ((pa[x - MID][y >> 5] >> y) & 1);
		ans[m++] = r["SC"];
		if (r) x--;
		else y--;
		if (x < 0 || y < 0) for(;;);
	}
	reverse(ans, ans+m);

	if (m != l2 + l1 - 2) for(;;);
	int ss = 0;
	x = y = 0;
	forn(i, l1+l2-2)
	{
		ss += f(x, y);
		if (ans[i] == 'C') x++;
		else y++;
	}
	ss += f(x, y);
	if (ss != xx) for(;;);
	ans[m] = '\0';
	puts(ans);

#ifdef ROOM_311
	time_t et_1 = clock();
	fprintf(stderr, "execution time = %0.0lf ms\n", (et_1 - et_0) * 1000.0 / CLOCKS_PER_SEC);
#endif
	return 0;
}

Little Gerald and his coach Mike play an interesting game. At the beginning of the game there is a pile consisting of n candies and a pile consisting of m stones. Gerald and Mike move in turns, Mike goes first. During his move Mike checks how many candies and stones Gerald has eaten. Let Gerald eat a candies and b stones. Then Mike awards Gerald f(a,b) prize points. Gerald during his move either eats a candy from the pile of candies or a stone from the pile of stones. As Mike sees that Gerald has eaten everything apart one candy and one stone, he awards points for the last time and the game ends. Gerald is not allowed to eat all the candies, and he is not allowed to eat all the stones too. Tell Gerald how to play to get the largest possible number of points: it is required to find one of the possible optimal playing strategies for Gerald.


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <memory.h>
#include <cmath>
#include <algorithm>
#include <queue>
#define vvi vector <vector <int> >
#define ll long long
#define vi vector <int>
#define task "fliptile"

using namespace std;

const int INF = 1000*1000*1000;

int main()
{
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    int m[1000*1000 + 5];
    int aa;
    memset(m, 0, sizeof(m));
    for(int i = 0; i < n; ++i) {
        cin >> aa;
        m[aa] = i;
    }
    vector <int> s(n);
    for(int i = 0; i < n; ++i) {
        cin >> aa;
        s[i] = m[aa];
    }
    reverse(s.begin(), s.end());
    //for(int i = 0; i < s.size(); ++i)
        //cout << s[i] << " ";
    //cout << endl;
    vector <int> a(n + 1, INF);
    a[0] = -INF;
    vector <int> p(n + 1, -1);
    vector <int> num(n + 1, -1);
    for(int i = 0; i < n; ++i) {
        size_t j = upper_bound(a.begin(), a.end(), s[i]) - a.begin();
        if(j != 0) {
            a[j] = s[i];
            num[j] = i;
            p[num[j]] = num[j - 1];
        }
    }
    vector <int> ans;
    //for(int i = 0; i < n; ++i)
        //cout << a[i] << endl;
    for(size_t i = a.size() - 1; i >= 1; --i) {
        if(a[i] != INF) {
            for(int cur = num[i]; cur != -1; cur = p[cur])
                ans.push_back(a[cur]);
            break;
        }
    }
    cout << ans.size() << endl;
    return 0;
}

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
#define MAXN 1000001

int revA[MAXN];
int perm[MAXN];
int LIS[MAXN];
int N;
int inline calc_lis()
{
	int l = 0;
	LIS[l++] = perm[0];
	for(int i=1;i<N;i++)
	{
		if(perm[i] > LIS[l-1])
		LIS[l++] = perm[i];
		else
		{
			int j = (int)(upper_bound(LIS,LIS+l,perm[i])-LIS);
			LIS[j] = perm[i];
		}
		/*
		printf("LIS:");
		for(int j=0;j<l;j++)
		printf("%d ",LIS[j]);
		printf("\n");
		*/
	}
	return l;
}
int main()
{
	scanf("%d",&N);

	for(int i=0;i<N;i++)
	{
		int x;
		scanf("%d",&x);
		revA[x-1] = i;
	}
	for(int i=0;i<N;i++)
	{
		int x;
		scanf("%d",&x);
		perm[i] = -revA[x-1];
	}
	/*
	for(int i=0;i<N;i++)
	printf("%d ",perm[i]);
	printf("\n");
	*/
	//find LIS of perm
	printf("%d\n",calc_lis());
	return 0;
}

Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=1000000+10;
int n,m,d[maxn],ans,vis[maxn],cnt,a,b;
vector<int> g[maxn];
int dfs(int x)
{
	vis[x]=cnt; int sum=0;
	if(d[x]&1) sum++;
	for(int i=0;i<g[x].size();i++)
		if(!vis[g[x][i]])
			sum+=dfs(g[x][i]);
	return sum;
}
int main()
{
	scanf("%d %d",&n,&m);
	d[1]+=2,g[1].push_back(1);
	for(int i=0;i<m;i++)
	{
		scanf("%d %d",&a,&b);
		d[a]++,d[b]++;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	for(int i=1;i<=n;i++)
		if(!vis[i] && d[i])
		{
			cnt++,a=dfs(i)/2;
			ans+=a?a-1:a;
		}
	if(cnt==1)
	{
		if(a!=0) ans++;
		cnt=0;
	}
	printf("%d\n",ans+cnt);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
int deg[2000005],vis[2000005];
vector<int> v[2000005];
int bfs(int m)
    {

    int res = 0;
    queue<int> q;
    q.push(m);
    vis[m] = 1;
    int i,l,cur,x;
    while(!q.empty())
        {
        cur = q.front();
        q.pop();
        res += deg[cur];
        l = v[cur].size();
        for(i=0;i<l;i++)
            {
            x = v[cur][i];
            if(vis[x]==0)
                {
                vis[x] = 1;
                q.push(x);
            }
        }
    }
    return res;

}
int main()
    {
    int n,m;
    scanf("%d%d",&n,&m);
    int i,x,y;
    for(i=1;i<=m;i++)
        {
        scanf("%d%d",&x,&y);
        deg[x]^=1;
        deg[y]^=1;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    int ans = 0,full=0;
    vector<int> components;
    for(i=1;i<=n;i++)
        {
        if(vis[i]==0)
            {
            int cur = bfs(i);
            ans += cur;
            if(cur==0)
                {
                if(i==1 || v[i].size())full++;
            }
            if(i==1 || v[i].size())components.push_back(cur);
        }
    }
    ans/=2;
    if(components.size()>1)ans += full;
    printf("%d\n",ans);
}

Vasya went for a walk in the park. The park has n glades, numbered from 1 to n. There are m trails between the glades. The trails are numbered from 1 to m, where the i-th trail connects glades xi and yi. The numbers of the connected glades may be the same (xi=yi), which means that a trail connects a glade to itself. Also, two glades may have several non-intersecting trails between them.Vasya is on glade 1, he wants to walk on all trails of the park exactly once, so that he can eventually return to glade 1. Unfortunately, Vasya does not know whether this walk is possible or not. Help Vasya, determine whether the walk is possible or not. If such walk is impossible, find the minimum number of trails the authorities need to add to the park in order to make the described walk possible.Vasya can shift from one trail to another one only on glades. He can move on the trails in both directions. If Vasya started going on the trail that connects glades a and b, from glade a, then he must finish this trail on glade b.


//Pham Huu Canh
//A. Cottage Village
//Algorithm:
//Complexity:
//AC:

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

#define max64 9223372036854775807LL
#define max32 2147483647
#define maxty 1001001001
#define max16 32767
#define EPS 1e-8
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define PQ priority_queue
#define LB lower_bound
#define UB upper_bound
#define fi first
#define se second
#define timmax(x, y)    ((x) > (y) ? (x) : (y))
#define timmin(x, y)    ((x) < (y) ? (x) : (y))
#define fori(i, n)      for((i) = 0; (i) < (n); (i)++)
#define ford(i, n)      for((i) = (n-1); (i) >= 0; (i)--)
#define fore(i, v)		for(typeof(v.begin()) i = v.begin(); i != v.end(); i++)
#define repi(i, a, b)   for((i) = (a); (i) <= (b); (i)++)
#define repd(i, a, b)   for((i) = (a); (i) >= (b); (i)--)
#define all(tmpv)      tmpv.begin(), tmpv.end()

#define fii "a.inp"
#define foo "a.out"
#define MOD 1000000007
#define inf 1000111000111000111LL

using namespace std;

typedef pair<int, int> II;
typedef vector<int> VI;

int cal(II p1, II p2, int t){
	double sz = ((double)p2.fi - (double)p2.se/2.0) - ((double)p1.fi + (double)p1.se/2.0);
	if (fabs(sz - t) <= EPS)	return 1;
	else if (sz > t)			return 2;
	return 0;
}

void input()
{
	int i, n, res, t;
	II p[1005];

	scanf("%d %d", &n, &t);
	fori(i, n)	scanf("%d %d", &p[i].fi, &p[i].se);

	res = 2;
	sort(p, p + n);
	fori(i, n-1)	res += timmin(2, cal(p[i], p[i+1], t));

	printf("%d", res);
}

int main()
{
    #ifndef ONLINE_JUDGE
    	freopen(fii,"r",stdin);
    	freopen(foo,"w",stdout);
    #endif

    input();

    return 0;
}

A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?


#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <bitset>
#include <set>
#include <map>
#include <vector>
#include <complex>

using namespace std;
typedef complex<double> P;

#define EPS (1e-10)
#define EQ(a,b) (abs((a)-(b)) < EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )

int main(){
  int n,g[999999],cnt,sum;
  cin>>n;
  for(int i=0;i<n;i++)cin>>g[i];

  for(int i=1;i*3<=n;i++){
    if((n%i==0)){

      for(int j=0;j<n;j++){int flag=1;
    for(sum=j,cnt=0;sum-j<n;sum+=i){

      //if(g[sum])cnt++;
      //if(cnt==n/i){cout<<"YES";return 0;}
      if(!g[sum%n]){flag=0;break;}

    }
    if(flag){cout<<"YES";return 0;}
    //cout<<cnt<<endl;
      }
    }
  }
  cout<<"NO";
  return 0;

}

/*
 * test.cpp
 *
 *  Created on: 2012-1-12
 *      Author: Administrator
 */

//Round Table Knights
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

int prime[20000] =
  { 2, 3, 5, 7, 11, 13, 17, 19 };
int table[100006];
int yinzi[10];
int yinzishu = 0;
bool qumo[10][100006];
void
getprime()
{
  int n = 8;
  for (int i = 23; i < 110000; i += 2)
    {
      int t = i / 2;
      bool flag = true;
      for (int j = 1; prime[j] < t; j++)
        {
          if (!(i % prime[j]))
            {
              flag = false;
              break;
            }
        }
      if (flag)
        {
          prime[n++] = i;
        }
    }
//  cout << n << endl;
}
int
main()
{
  getprime();
//  for(int i=0;i!=11;i++)
//    {
//      cout<<prime[i]<<endl;
//    }
  memset(qumo, 1, sizeof(qumo));
  int n;
  scanf("%d", &n);
  for (int i = 0; i != n; i++)
    {
      scanf("%d", table + i);
    }
  int t = n;
  yinzishu=0;
  for (int i = 1; prime[i] <= t ; i++)
    {
      if(!(t % prime[i]))
        {
          yinzi[yinzishu++]=prime[i];
        }
      while(!(t%prime[i]))
        {
          t/=prime[i];
        }
    }
  if(!(t%4))
    yinzi[yinzishu++]=4;
  for(int i=0;i!=yinzishu;i++)
    {
      yinzi[i]=n/yinzi[i];
//      cout<<yinzi[i]<<endl;
    }
  for(int i=0;i!=n;i++)
    {
      if(!table[i])
        {
          for(int j=0;j!=yinzishu;j++)
            {
              qumo[j][i%yinzi[j]]=0;
            }
        }
    }
  int ans=0;
  for(int i=0;i!=yinzishu;i++)
    {
      for(int j=0;j<yinzi[i];j++)
        {
          if(qumo[i][j])
            {
//            cout<<yinzi[i]<<" "<<j<<endl;
              ans=1;
              break;
            }
        }
    }
  if(ans)
    printf("YES\n");
  else
    printf("NO\n");
}

There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.


#include<cstdio>
#include<vector>
#include<algorithm>
#include<iostream>
#include<cstring>

using namespace std;

int vis[100010];
long long int cnt[100010];
int CC[100010];
vector<int> V[100010];
int cc=1;

void dfs(int cur) {
	if (vis[cur]) return ;
	vis[cur]=1;
	int l=V[cur].size();
	for (int i=0;i<l;i++) {
		CC[V[cur][i]]=cc;
		dfs(V[cur][i]);
	}
}

int main()
{
	memset(vis,0,sizeof vis);
	memset(cnt,0,sizeof cnt);
	long long int n,m,mod;
	cin >> n >> m >> mod;
	for(int i=0;i < m; i++)
	{
		int x,y;
		cin >> x >> y;
		V[x].push_back(y);
		V[y].push_back(x);
	}
	for (int i=1;i<=n;i++) {
		if (!vis[i]) {
			CC[i]=cc;
			dfs(i);
			cc++;
		}
	}
	for (int i=1;i<=n;i++) {
		cnt[CC[i]]++;
	}
	int N = 0;
	long long int val = 1;
	for (int i=1;i<=n;i++) {
		if (cnt[i]) {
			N++;
			val=(val*cnt[i])%mod;
		}
	}
	if (N==1) cout << 1%mod << endl;
	else {
		for (int i=N-2;i>0;i--) val=(val*n)%mod;
		cout << val << endl;
	}
	return 0;
}

#include <cstdio>

using namespace std;

#define MAXN 100005

int parent[MAXN];
int C,cont[MAXN];

int Find(int x){
    if(parent[x] != x) parent[x] = Find(parent[x]);
    return parent[x];
}

void Union(int x, int y){
    x = Find(x); y = Find(y);

    if(x != y){
        parent[x] = y;
        cont[y] += cont[x];
        --C;
    }
}

int main(){
    int n,m,k;

    scanf("%d %d %d",&n,&m,&k);

    C = n;

    for(int i = 1;i <= n;++i){
        parent[i] = i;
        cont[i] = 1;
    }

    for(int i = 0,u,v;i < m;++i){
        scanf("%d %d",&u,&v);
        Union(u,v);
    }

    int ans = 1 % k;

    if(C >= 2){
        for(int i = 1;i <= n;++i)
            if(Find(i) == i)
                ans = (long long)ans * cont[i] % k;

        for(int i = 1;i <= C - 2;++i)
            ans = (long long)ans * n % k;
    }

    printf("%d\n",ans);

    return 0;
}

As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k.


#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

string buscaMenor(string a, string b, vector<string>& v) {
    for (int i = 0; i < v.size(); ++i) if (v[i] >= b and v[i] < a) return v[i];
    return "";
}

string buscaMayor(string a, string b, vector<string>& v) {
    for (int i = 0; i < v.size(); ++i) if (v[i] >= b) return v[i];
    return "";
}

string toStr(int x) {
    string s;
    do {
        s += char(x%10 + '0');
        x /= 10;
    } while (x > 0);
    reverse(s.begin(), s.end());
    return s;
}

int main() {
    map<string, vector<string> > adj1, adj2;
    for (int i = 1000; i <= 9999; ++i) {
        string s = toStr(i);
        for (int j = 3; j >= 0; --j) {
            for (int k = s[j] - '0' + 1; k < 10; ++k) {
                string r = s;
                r[j] = k + '0';
                if (r <= "2011") adj1[s].push_back(r);
                adj2[r].push_back(s);
            }
        }
    }
    int n;
    cin >> n;
    vector<string> v(n);
    for (int i = 0; i < n; ++i) cin >> v[i];
    string ant = "1000";
    bool ok = true;
    for (int i = 0; i < n and ok; ++i) {
        if (ant < v[i]) {
            string s = buscaMenor(v[i], ant, adj2[v[i]]);
            if (s != "") v[i] = s;
            ant = v[i];
            if (ant > "2011") ok = false;
        }
        else if (v[i] < ant) {
            v[i] = buscaMayor(v[i], ant, adj1[v[i]]);
            if (v[i] == "") ok = false;
            ant = v[i];
        }
    }
    if (ok) for (int i = 0; i < n; ++i) cout << v[i] << endl;
    else cout << "No solution" << endl;
}

The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.


#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;

#define DEBUG(x) cout << ">>> " << #x << " : " << x << endl;
#define REP(i,a) for (int i = 0; i < (a); ++i)
#define FOR(i,a,b) for (int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for (int i = (a); i >= (b); --i)
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }

const int INF = 1<<29;
typedef long long ll;
///////////////////////////////////////////////////////////////////////////

#define max 400001
char input[max];
int sep[max];

int main()
{
memset(sep,0,sizeof(sep));
memset(input,0,sizeof(input));
int i = 0;
scanf("%s",input);
if(input[i]==0) {printf("YES\n"); return 0;}
if(input[i]=='.') {printf("NO\n"); return 0;}
int start = -1;
while(input[i]!=0 && i<=8){
	if(input[i]=='.') {start = i; break;}
	else i++;
}
if(start==-1) {printf("NO\n"); return 0;}
i = start+1;
while(input[i]!=0){
	if(i-start>=13) {printf("NO\n"); return 0;}
	if(input[i]=='.'){
		if(i-start<3) {printf("NO\n"); return 0;}
		if(i-start>=11) sep[start+3]=1;
		else sep[start+1]=1;
		start = i;
	}
	i++;
}
if(i-start>4 || i-start==1) {printf("NO\n"); return 0;}
else sep[i-1]=1;

i = 0;
printf("YES\n");
while(input[i]!=0){
printf("%c",input[i]);
if(sep[i]) printf("\n");
i++;
}
return 0;
}

#include <cstdlib>
#include <iostream>
#include <set>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#define pb push_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
using namespace std;
typedef long long LL;
vector<string> ans;
int main(int argc, char *argv[])
{
    char s[400100];
    scanf("%s",&s);
    long h=strlen(s);
    if(s[h-1]=='.' || s[0]=='.')return puts("NO")&0;
    string qqq=s;
    long r=qqq.find("..");
    if(r!=string::npos)return puts("NO")&0;
    r=qqq.find(".");
    if(r==string::npos)return puts("NO")&0;
    int g=0;
    string qq,a;
    char * pch;
    pch=strtok(s,".");
    while(pch!=NULL){
                    qq=pch;
                    if(g==0){
                             if(qq.size()>8)return puts("NO")&0;
                             a=qq;
                             g++;
                             pch=strtok(NULL,".");
                             continue;
                             }
                    if(a.size()==0)return puts("NO")&0;
                    if(qq.size()>11)return puts("NO")&0;
                    ans.pb(a);
                    ans.back()+=".";
                    ans.back()+=qq.substr(0,qq.size()<=8 ? 1:qq.size()-8);
                    a=qq.substr(qq.size()<=8 ? 1:qq.size()-8,qq.size());
                    pch=strtok(NULL,".");
                    }
    if(a.size()>2)return puts("NO")&0;
    ans.back()+=a;
    puts("YES");
    for(int i=0;i<ans.size();i++)printf("%s\n",ans[i].c_str());

    return 0;
}

Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where:   name is a string consisting of lowercase Latin letters, its length is from 1 to 8 characters;  ext is a string consisting of lowercase Latin letters, its length is from 1 to 3 characters. For example, "read.me", "example.txt" and "b.cpp" are valid file names and "version.info", "ntldr" and "contestdata.zip" are not.Damage to the list meant that all the file names were recorded one after another, without any separators. So now Eudokimus has a single string.Eudokimus needs to set everything right as soon as possible. He should divide the resulting string into parts so that each part would be a valid file name in BerFS. Since Eudokimus has already proved that he is not good at programming, help him. The resulting file list can contain the same file names.

[{'input': 'read.meexample.txtb.cpp\n', 'output': ['YES\nread.m\neexample.t\nxtb.cpp\n']}, {'input': 'version.infontldrcontestdata.zip\n', 'output': ['NO\n']}, {'input': 'thisis.text.txt\n', 'output': ['YES\nthisis.t\next.txt\n']}, {'input': 'oops.t\n', 'output': ['YES\noops.t\n']}, {'input': 'thisislongfilename\n', 'output': ['NO\n']}, {'input': 'double..dot\n', 'output': ['NO\n']}, {'input': 'one.one.one.one.one.one.one.one.one.one\n', 'output': ['YES\none.o\nne.o\nne.o\nne.o\nne.o\nne.o\nne.o\nne.o\nne.one\n']}, {'input': '.\n', 'output': ['NO\n']}, {'input': 'z\n', 'output': ['NO\n']}, {'input': 'a.\n', 'output': ['NO\n']}, {'input': '.a\n', 'output': ['NO\n']}, {'input': 'za\n', 'output': ['NO\n']}, {'input': '..\n', 'output': ['NO\n']}, {'input': 'xlq\n', 'output': ['NO\n']}, {'input': '.r.\n', 'output': ['NO\n']}, {'input': 'ulmc\n', 'output': ['NO\n']}, {'input': 'nja.\n', 'output': ['NO\n']}, {'input': 't..kz\n', 'output': ['NO\n']}, {'input': 'twaha\n', 'output': ['NO\n']}, {'input': 'm..dw.\n', 'output': ['NO\n']}, {'input': 'utsvfg.\n', 'output': ['NO\n']}, {'input': '.we.voae\n', 'output': ['NO\n']}, {'input': 'kw.gkcxk.\n', 'output': ['NO\n']}, {'input': '.c.v.hpehh\n', 'output': ['NO\n']}, {'input': 'akymwh\n', 'output': ['NO\n']}, {'input': 'jx.lqv.\n', 'output': ['NO\n']}, {'input': 'qkwtq.zw\n', 'output': ['YES\nqkwtq.zw\n']}, {'input': 'yxwvlk..b\n', 'output': ['NO\n']}, {'input': 'ph..qlr.pt\n', 'output': ['NO\n']}, {'input': 'cab.ab.bac\n', 'output': ['YES\ncab.a\nb.bac\n']}, {'input': 'badaba.ae\n', 'output': ['YES\nbadaba.ae\n']}, {'input': 'badabaca.mor\n', 'output': ['YES\nbadabaca.mor\n']}, {'input': 'bae.a\n', 'output': ['YES\nbae.a\n']}, {'input': 'b.baba.ebpbac.iabaeabac.abab.adabacaba.ahcggibij.adaacab.ebaba.aa.abacaba.dacabada.daqjcpc.jadab.dab\n', 'output': ['YES\nb.b\naba.e\nbpbac.i\nabaeabac.a\nbab.a\ndabacaba.a\nhcggibij.a\ndaacab.e\nbaba.a\na.a\nbacaba.d\nacabada.d\naqjcpc.j\nadab.dab\n']}, {'input': '.ab\n', 'output': ['NO\n']}, {'input': 'aa.aa.aaaabbbbccc.ddd.ee\n', 'output': ['YES\naa.a\na.aaa\nabbbbccc.d\ndd.ee\n']}, {'input': 'a.aaaa\n', 'output': ['NO\n']}, {'input': 'aaaaread.meexample.txtb.cpp\n', 'output': ['YES\naaaaread.m\neexample.t\nxtb.cpp\n']}, {'input': 'abcdabcd.a\n', 'output': ['YES\nabcdabcd.a\n']}, {'input': 'qwertyuio.qwe\n', 'output': ['NO\n']}, {'input': 'asd.\n', 'output': ['NO\n']}, {'input': 'aaaaaaaa.\n', 'output': ['NO\n']}, {'input': 'a.txtaaaaaaaaa.txt\n', 'output': ['NO\n']}, {'input': '.abcde.cpp\n', 'output': ['NO\n']}, {'input': '.abc.cpp\n', 'output': ['NO\n']}, {'input': 'abcdefgh.aaaabcdefgh.bbb\n', 'output': ['YES\nabcdefgh.aaa\nabcdefgh.bbb\n']}, {'input': 'filename.exe\n', 'output': ['YES\nfilename.exe\n']}, {'input': '.abcd.cpp\n', 'output': ['NO\n']}, {'input': 'abc.bcdabcdabcd.abc\n', 'output': ['YES\nabc.bcd\nabcdabcd.abc\n']}, {'input': 'abc.abcde\n', 'output': ['NO\n']}, {'input': 'a.cp\n', 'output': ['YES\na.cp\n']}, {'input': 'a.b.c\n', 'output': ['NO\n']}, {'input': '.ha\n', 'output': ['NO\n']}, {'input': 'a.a.a.a\n', 'output': ['NO\n']}, {'input': 'a.a.a\n', 'output': ['NO\n']}, {'input': 'qwertyui.cp\n', 'output': ['YES\nqwertyui.cp\n']}, {'input': 'ss.aaaaaaaaaaaa.aa\n', 'output': ['NO\n']}, {'input': 'name.extnamename.ext\n', 'output': ['YES\nname.ext\nnamename.ext\n']}, {'input': '.aaaa.aaa\n', 'output': ['NO\n']}, {'input': 'aaaaaaaaaaaaaaaaaaaa.a\n', 'output': ['NO\n']}, {'input': '.filena.exe\n', 'output': ['NO\n']}, {'input': 'a.aaaaaaaaaaa.a\n', 'output': ['YES\na.aaa\naaaaaaaa.a\n']}, {'input': '.aa.w\n', 'output': ['NO\n']}]


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

#define bublic public
#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define sz size()
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define ford(i, n) for(int i=(n)-1; i>=0; i--)
#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)

template <class _T> inline _T sqr(const _T& x) { return x * x; }
template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); }

typedef long double ld;

// Constants
const ld PI = 3.1415926535897932384626433832795;
const ld EPS = 1e-11;

// Types
typedef signed   long long i64;
typedef unsigned long long u64;
typedef set < int > SI;
typedef vector < int > VI;
typedef map < string, int > MSI;
typedef pair < int, int > PII;

#define BASE 10000

int bb[1024000];
int nn[1024000];
int c;
char sb[1024000];
char sn[1024000];
int ps[128];
int cs[128];
int as[128];
int ind[128];
int fc;

int modak(int *a, int k)
{
	int j = 0;
	Ford(i, a[0], 1)
	{
		j = ((i64)j * BASE + a[i]) % k;
	}
	return j;
}

int mypow(int a, int k, int p)
{
	int ans = 1;
	int j = 1 << 30;
	while (j)
	{
		ans = (i64)ans * ans % p;
		if (j & k) ans = (i64)ans * a % p;
		j >>= 1;
	}
	return ans;
}

int toint(int *a)
{
	if (a[0] > 3 || (a[0] == 3 && a[a[0]] > 10)) return 1000000001;
	int x = 0;
	Ford(i, a[0], 1)
	{
		x = x * BASE + a[i];
	}
	return min(x, 1000000001);
}

int calc(int p, int k)
{
	int ans = 1;
	int r = 1;
	forn(i, k)
	{
		r *= p;
	}

	int fc = p-1;
	forn(i, k-1)
	{
		fc *= p;
	}
	int nnn = toint(nn);
//	cerr << "r = " << r << endl;
//	cerr << "fc = " << fc << endl;
	int b1 = modak(bb, r);
//	cerr << bb[0] << " " << bb[1] << endl;
//	cerr << "b1 = " << b1 << endl;
	ans = (i64)ans * (b1-1+r) % r;
	if (b1 % p == 0)
	{
		if (nnn > k)
		{
			return 0;
		}
		else
		{
//			cerr << "ans = " << ans << endl;
			ans = (i64)ans * mypow(b1, nnn-1, r) % r;
//			cerr << "ans = " << ans << endl;
		}
	}
	else
	{
		int t = (modak(nn, fc) - 1 + fc) % fc;
//		cerr << "t = " << t << endl;
		ans = (i64)ans * mypow(b1, t, r) % r;
	}

	return ans;
}

bool cmp(int p1, int p2)
{
	return pow(ps[p1], cs[p1]) > pow(ps[p2], cs[p2]);
}

int main()
{
#ifdef ROOM_311
	freopen("input.txt", "rt", stdin);
	freopen("output.txt", "wt", stdout);
#endif
	cout << setiosflags(ios::fixed) << setprecision(10);

	clr(bb);
	clr(nn);
	scanf("%s%s%d", sb, sn, &c);
	if (c == 1)
	{
		puts("1");
		return 0;
	}
	int lb = strlen(sb);
	int ln = strlen(sn);
	bb[0] = (lb + 3) / 4;
	nn[0] = (ln + 3) / 4;
	For(i, 1, bb[0])
	{
		forn(j, 4)
		{
			bb[i] = bb[i] * 10 + ((lb - i * 4 + j >= 0) ? (sb[lb - i * 4 + j] - '0') : 0);
		}
	}
	For(i, 1, nn[0])
	{
		forn(j, 4)
		{
			nn[i] = nn[i] * 10 + ((ln - i * 4 + j >= 0) ? (sn[ln - i * 4 + j] - '0') : 0);
		}
	}
	fc = 1;
	int x = c;
	int m = 0;
	for(int i = 2; i * i <= x; i++)
	{
		if (x % i == 0)
		{
			x /= i;
			fc *= i-1;
			ps[m] = i;
			cs[m] = 1;
			while (x % i == 0)
			{
				x /= i;
				fc *= i;
				cs[m]++;
			}
			m++;
		}
	}
	if (x > 1)
	{
		ps[m] = x;
		cs[m] = 1;
		m++;
		fc *= x-1;
		x /= x;
	}

	forn(i, m)
	{
		as[i] = calc(ps[i], cs[i]);
		ind[i] = i;
	}
	sort(ind, ind+m, cmp);
	int ans = as[ind[0]];
	int r = 1;
	forn(j, cs[ind[0]])
	{
		r *= ps[ind[0]];
	}
	For(i1, 1, m-1)
	{
		int i = ind[i1];
		int z = 1;
		forn(j, cs[i])
		{
			z *= ps[i];
		}
		while (ans % z != as[i]) ans += r;
		r *= z;
	}
//	forn(i, m)
//	{
//		cerr << ps[i] << " " << cs[i] << " " << as[i] << endl;
//	}

	if (ans <= 0) ans += c;

	printf("%d\n", ans);

	return 0;
}

#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

ll calcMod(const string &s, ll m) {
  ll a = 0;
  REP(i,s.size()) {
    a = a*10 + s[i]-'0';
    a %= m;
  }
  return a;
}

// xは1桁
char out[1000001];
string sub(const string &s, int x) {
  string ans;
  for (int i=s.size()-1; i>=0; --i) {
    int t = s[i]-'0'-x;
    if (t < 0) t += 10, x = 1;
    else x = 0;
    out[i] = t+'0';
  }
  return string(out);
}

ll u[1000001];

ll powmod(ll x, const string &n, ll mod) {
  u[0] = 1;
  u[1] = x%mod;
  for (int i=1; i<1000000; ++i) {
    u[i+1] = 1;
    REP(j,10) u[i+1] = (u[i+1] * u[i]) % mod;
  }
  ll ans = 1;
  REP(i, n.size()) {
    REP(j,n[i]-'0') ans = (ans * u[n.size()-i]) % mod;
  }
  //cout << x << " " << n << " " << mod << " " << ans << endl;
  return ans;
}

char b[1000001];
char n[1000001];
ll c;

int main() {
  scanf("%s %s", b, n);
  cin >> c;
  ll a = calcMod(b, c);
  string n1 = sub(n,1);
  ll ans = (powmod(a, n1, c) * (a-1) % c + c) % c;
  cout << (ans?ans:c) << endl;
}

Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.


#define TASKNAME "text"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cstdlib>
#include <cassert>
#include <functional>
#include <iomanip>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <vector>

#define EPS (1e-9)
#define INF (int(1e9))
#define INFLONG (long long)(1e18)
#define sqr(a) ((a) * (a))
#define all(a) (a).begin(), (a).end()
#define zero(a) memset(a, 0, sizeof(a))
#define abs(a) (((a) < 0) ? -(a) : (a))
#define sz(a) (int)a.size()
#define fst first
#define snd second
#define y1 osrughosduvgarligybakrybrogvba
#define y0 aosfigdalrowgyalsouvgrlvygalri
#define mp make_pair
#define pb push_back
#define next dlkjdslfkdj
#define prev dsdflksdfjl
#define hash lkdfjldskfj
#define pi 3.1415926535897932384626433832795
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

using namespace std;

typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
typedef vector <vi> vvi;
typedef vector <bool> vb;
typedef vector <ll> vll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair <ll, int> pli;
typedef pair <int, ll> pil;
typedef vector <pii> vpii;

const int max_it = 1e6;

int main()
{
  #ifdef LocalHost
    freopen(TASKNAME".in", "r", stdin);
    freopen(TASKNAME".out", "w", stdout);
  #endif
  int n, max_health, regeneration;
  scanf("%d%d%d", &n, &max_health, &regeneration);
  vi power(n), damage(n);
  for (int i = 0; i < n; i++)
    scanf("%d%d", &power[i], &damage[i]);

  int now_health = max_health;
  int it = 0;
  int sum_damage = 0;

  vpii ans;
  vb was(n, 0);
  while (now_health > 0 && it < max_it)
  {
    now_health -= sum_damage;
    now_health = min(max_health, now_health + regeneration);
    if (now_health <= 0)
      break;

    int max_damage = -1, idx = -1;
    for (int i = 0; i < n; i++)
    {
      if (!was[i] && max_health * power[i] >= now_health * 100 && max_damage < damage[i])
        max_damage = damage[i], idx = i;
    }
    if (idx != -1)
      was[idx] = 1, ans.pb(mp(it, idx + 1)), sum_damage += damage[idx];
    ++it;
  }
  printf("%s\n", it >= max_it ? "NO" : "YES");
  if (it < max_it)
  {
    printf("%d %d\n", it, sz(ans));
    for (int i = 0; i < sz(ans); i++)
      printf("%d %d\n", ans[i].fst, ans[i].snd);
  }
  return 0;
}

Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive (≤0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.


#include<vector>
#include<list>
#include<map>
#include<set>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<algorithm>
#include<functional>
#include<numeric>
#include<utility>
#include<iostream>
#include<sstream>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<climits>
using namespace std;
char s[40];
struct node
{
        char s[40];
        int o;
}nd[70];
int main()
{
        int n,m,i,j,k;
        scanf("%d%d",&n,&m);
        scanf("%s%d",s,&k);
        for (i=0;i<m-1;i++)
        {
                scanf("%s%d",nd[i].s,&nd[i].o);
        }
        m--;
        char t[50]={0};
        int ans=0;
        for (long long comb = (1LL << k) - 1; comb < 1LL << n;)
        {
                for (i=0;i<n;i++)
                {
                        if (comb&(1LL<<i))
                        {
                                t[i]=s[i];
                        }
                        else
                        {
                                t[i]=s[i]=='1'?'0':'1';
                        }
                }
                for (i=0;i<m;i++)
                {
                        int tmp=0;
                        for (j=0;j<n;j++)
                        {
                                if (t[j]==nd[i].s[j])++tmp;
                        }
                        if (tmp!=nd[i].o)break;
                }
                if (i==m)ans++;
                long long x = comb & -comb, y = comb + x;
                comb = ((comb & ~y) / x >> 1) | y;
        }
        printf("%d\n",ans);
        return 0;
}

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;

void inputSet(set <string> &S)
{
	string str, ss, so;
	int c, i, n;
	cin>>str>>c;
	n=str.size();
	for (i=0; i<c; i++) ss+='0';
	for (i=0; i<n-c; i++) ss+='1';
	so=ss;
	S.clear();
	do {
		for (i=0; i<n; i++) so[i]=str[i]^(1&ss[i]);
		S.insert(so);
	} while (next_permutation(ss.begin(), ss.end()));
}

int main()
{
	int n, m;
	set <string> S1, S2, S3;
	cin>>n>>m;
	inputSet(S1);
	while (--m) {
		inputSet(S2);
		set_intersection(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(S3, S3.begin()));
		S1=S3;
		S3.clear();
	}
	cout<<S1.size()<<endl;
	return 0;
}

Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.


// Authored by dolphinigle
// CodeForces 79
// 3 Aug 2011

#include <vector>
#include <list>
#include <map>
#include <set>

#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>

#define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define DEBUG(x) cout << '>' << #x << ':' << x << '\n';

#define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X))
#define RESET(Z,Y) memset(Z,Y,sizeof(Z))

#define SZ(Z) ((int)Z.size())
#define ALL(W) W.begin(), W.end()
#define PB push_back

#define MP make_pair
#define A first
#define B second

#define INF 1023123123
#define EPS 1e-11

#define MX(Z,Y) Z = max((Z),(Y))
#define MN(X,Y) X = min((X),(Y))

#define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++)

using namespace std;

typedef long long ll;
typedef double db;
typedef vector<int> vint;
typedef vector<ll> vll;

//O(n log n)
vector<int> SequenceSimplify(vector<int> seq) {
	int lowest = 0;
	vector<int> disort = seq;
	sort(ALL(disort));
	disort.erase(unique(ALL(disort)),disort.end());
	FORN(i,SZ(seq)) {
		seq[i] = (lower_bound(ALL(disort),seq[i]) - disort.begin()) + lowest;
		}
	return seq;
	}

//vint a = {10, 50, 5, 50, 10, 70}
//SequenceSimplify(a) = {1, 2, 0, 2, 1, 3}

ll modu = 1000000007LL;

//ONE indexed
struct FenwickTree {
	int n;
	ll bit[400005];
	FenwickTree (int _n) {
		n = _n;
		FORN(i,n) bit[i+1] = 0;
		}
	void add (int pos, ll val) {
		while (pos <= n) {
			bit[pos] += val;
      bit[pos] %= modu;
			pos += (pos & -pos);
    }
  }
	ll sum(int ending) {
		if (ending > n) ending = n;
		ll retval = 0;
		while (ending >= 1) {
			retval += bit[ending];
			ending -= (ending & -ending);
    }
		return retval % modu;
  }

	ll sumarea(int mulai, int selesai) {
		if (mulai > selesai) return 0LL;
		return (sum(selesai) - sum(mulai - 1) + modu) % modu;
  }
};

int main() {

  int n, m;
  cin >> n >> m;

  int target_ok = 0;
  int awal_ok = 0;

  vector<int> input;
  FORN(i, m) {
    int dari, ke;
    scanf("%d %d", &dari, &ke);
    input.PB(dari);
    input.PB(ke);
    if (ke == n) target_ok = 1;
    if (dari == 0) awal_ok = 1;
  }

  if (!target_ok || !awal_ok) {
    cout << 0LL << endl;
    return 0;
  }

  input = SequenceSimplify(input);
  FenwickTree tree(SZ(input)+10);

  int target = *max_element(ALL(input));

  vector< pair<int, int> > bus;
  FORN(i, m) {
    int dari, ke;
    dari = input[i*2];
    ke = input[i*2+1];
    bus.PB(MP(ke, dari));
  }

  sort(ALL(bus));

  tree.add(1, 1LL);
  FORN(i, m) {
    int dari = bus[i].B;
    int ke = bus[i].A;
    ++dari;
    ++ke;
    // ke = 3, dari = 2 itu sum dari [2, 3]
    ll jml = tree.sumarea(dari, ke-1LL);
    while (jml < 0LL) jml += modu;
    jml %= modu;
    tree.add(ke, jml);
  }

  cout << tree.sumarea(target+1, target+1) << endl;

  return 0;
}

# include <algorithm>
# include <bitset>
# include <cassert>
# include <cctype>
# include <cmath>
# include <complex>
# include <cstdio>
# include <cstdlib>
# include <cstring>
# include <ctime>
# include <deque>
# include <functional>
# include <iostream>
# include <iterator>
# include <list>
# include <map>
# include <numeric>
# include <queue>
# include <set>
# include <sstream>
# include <stack>
# include <string>
# include <valarray>
# include <vector>
# include <utility>

using namespace std ;

// Types
typedef long double ld ;
//typedef long long ll ;
typedef pair < int , int > pii ;
typedef vector < int > vi ;
typedef vector < pii > vp ;
typedef vector < ld > vd ;
typedef vector < string > vs ;
typedef vector < bool > vb ;
typedef queue < pii > qp ;
typedef map < string , int > msi ;

// Constants
const int INF = 1000000000 ;
const ld EPS = 1e-10L ;
const ld PI = 3.14159265358979L ;

//define

#define ijk() int i,j,k;
#define For(i,a,b) for(int i=(a);i<=(b);i++)
#define Ford(i,a,b) for(int i=(a);i>=(b);i--)
#define Rep(i,n) for(int i=0;i<(n);i++)
#define Repd(i,n) for(int i=(n)-1;i>0;i--)
#define maxv 1000007

struct Seg
{
    int st,en;
};

Seg seg[maxv],cseg[maxv];
set <int> si;
map <int,int>mii;

bool cmp(Seg a,Seg b){return a.en<b.en;}

vi adj[maxv];
int dp[maxv];
int mod=1000000007;
int tree[maxv];

int id,n,m;

int read(int idx)
{
    int sum = 0;
    while (idx > 0) sum =(sum+tree[idx])%mod , idx -= (idx & -idx);
    return sum;
}

void update(int idx ,int val)
{
    while (idx <= id) tree[idx]=(tree[idx]+val)%mod , idx += (idx & -idx);
}

int main()
{

    scanf("%d%d",&n,&m);
    n++;
    si.clear();
    si.insert(1);
    si.insert(n);

    Rep(i,m)
    {
        scanf("%d%d",&seg[i].st,&seg[i].en);
        seg[i].st++;seg[i].en++;
        si.insert(seg[i].st);si.insert(seg[i].en);
    }

    id=1;

    for(set<int>::iterator it=si.begin();it!=si.end();it++)
    {
        mii[*it]=id++;
    }

    id--;

    Rep(i,m)
    {
        cseg[i].st=mii[seg[i].st];cseg[i].en=mii[seg[i].en];
        adj[cseg[i].en].push_back(cseg[i].st);
    }

    update(1,1);
    For(i,2,id)
        Rep(j,adj[i].size())
            update(i,read(i-1)-read(adj[i][j]-1));

    printf("%d\n",(mod+read(mii[n])-read(mii[n]-1))%mod);

    return 0;
}

Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n+1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si<ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti-1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (10^9+7).


using System;
using System.Collections.Generic;
using System.Text;

namespace TaskA
{
    class Program
    {
        static int readInt()
        {
            String s = "";
            StringBuilder sb = new StringBuilder(12, 12);

            Char c = (Char)Console.Read();
            while (c == ' ' || c == '\n' || c == '\r') c = (Char)Console.Read();

            while (c != ' ' && c != '\n' && c != '\r')
            {
                sb.Append(c);
                c = (Char)Console.Read();
            }

            s = sb.ToString();
            return Int32.Parse(s);
        }

        static int[] readIntS(int n)
        {
            int[] na = new int[n];
            for (int i = 0; i < n; i++)
                na[i] = readInt();
            return na;
        }

        static void Main(string[] args)
        {
            int n = readInt();
            int[] di = readIntS(n - 1);
            int a = readInt();
            int b = readInt();

            int years = 0;
            for (int i = a-1; i < b-1; i++)
            {
                years += di[i];
            }

            Console.WriteLine(years);
        }
    }
}

using System;
using System.Linq;

namespace _38A
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());
            int[] cont = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int[] temp = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int pos = temp[0], dest = temp[1], ans = 0;
            for (int i = pos - 1; i <= dest - 2; i++)
                ans += cont[i];
            Console.WriteLine(ans);
        }
    }
}

The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i+1. Reaching a certain rank i having not reached all the previous i-1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.