結果

問題 No.3244 Range Multiple of 8 Query
コンテスト
ユーザー pengin_2000
提出日時 2025-08-22 23:23:02
言語 C
(gcc 15.2.0)
コンパイル:
gcc-15 -O2 -DONLINE_JUDGE -o a.out _filename_ -lm
実行:
./a.out
結果
AC  
実行時間 853 ms / 5,000 ms
コード長 1,423 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 201 ms
コンパイル使用メモリ 41,928 KB
最終ジャッジ日時 2026-02-22 13:44:05
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include<stdio.h>
char s[300005];
int a[300005];
int bef[300005][10];
int main()
{
	int n, q;
	scanf("%d %d", &n, &q);
	scanf("%s", s);
	int i, j;
	for (i = 0; i < n; i++)
		a[i] = s[i] - '0';
	for (j = 0; j < 10; j++)
		bef[0][j] = 0;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < 10; j++)
			bef[i + 1][j] = bef[i][j];
		bef[i + 1][a[i]] = i + 1;
	}
	int l, r;
	int ans, id[3], v[10], res;
	for (; q > 0; q--)
	{
		scanf("%d %d", &l, &r);
		if (r - l == 0)
		{
			if (a[l - 1] % 8 > 0)
				printf("-1\n");
			else
				printf("0\n");
		}
		else if (r - l == 1)
		{
			if ((10 * a[l - 1] + a[r - 1]) % 8 == 0)
				printf("0\n");
			else if ((10 * a[r - 1] + a[l - 1]) % 8 == 0)
				printf("1\n");
			else
				printf("-1\n");
		}
		else
		{
			ans = -1;
			for (i = 0; i < 1000; i += 8)
			{
				for (j = 0; j < 10; j++)
					v[j] = bef[r][j];
				int ii = i;
				for (j = 2; j >= 0; j--)
				{
					id[j] = v[ii % 10];
					if (v[ii % 10] > 0)
						v[ii % 10] = bef[id[j] - 1][ii % 10];
					ii /= 10;
				}
				res = 0;
				for (j = 0; j < 3; j++)
				{
					if (id[j] < l)
					{
						res = -1;
						break;
					}
					res += r - 2 + j - id[j];
				}
				if (res >= 0)
				{
					if (id[0] > id[1])
						res++;
					if (id[0] > id[2])
						res++;
					if (id[1] > id[2])
						res++;
				}
				if (res >= 0)
				{
					if (ans < 0 || ans > res)
						ans = res;
				}
			}
			printf("%d\n", ans);
		}
	}
	return 0;
}
0