結果

問題 No.3244 Range Multiple of 8 Query
ユーザー pengin_2000
提出日時 2025-08-22 23:23:02
言語 C
(gcc 13.3.0)
結果
AC  
実行時間 731 ms / 5,000 ms
コード長 1,423 bytes
コンパイル時間 784 ms
コンパイル使用メモリ 28,112 KB
実行使用メモリ 14,804 KB
最終ジャッジ日時 2025-08-22 23:23:39
合計ジャッジ時間 15,215 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 40
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.c: In function ‘main’:
main.c:8:9: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
    8 |         scanf("%d %d", &n, &q);
      |         ^~~~~~~~~~~~~~~~~~~~~~
main.c:9:9: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
    9 |         scanf("%s", s);
      |         ^~~~~~~~~~~~~~
main.c:25:17: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   25 |                 scanf("%d %d", &l, &r);
      |                 ^~~~~~~~~~~~~~~~~~~~~~

ソースコード

diff #

#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