Sure, here is the translated text:

```
II. (40 points) Let the sequence $\left\{a_{n}\right\}$ be defined as $a_{1}=1$,
$$
a_{n+1}=\left\{\begin{array}{ll}
a_{n}+n, & a_{n} \leqslant n ; \\
a_{n}-n, & a_{n}>n
\end{array}(n=1,2, \cdots) .\right.
$$

Find the number of positive integers $r$ that satisfy $a_{r}<r \leqslant 3^{2017}$.
```
From the definition of the sequence, we know $a_{1}=1, a_{2}=2$.
Assume for some integer $r \geqslant 2$, we have $a_{r}=r$, it is sufficient to prove that for $t=1,2, \cdots, r-1$, we have
$$
\left\{\begin{array}{l}
a_{r+2 t-1}=2 r+t-1>r+2 t-1, \\
a_{r+2 t}=r-tr+1, \\
a_{r+2}=a_{r+1}-(r+1)=2 r-(r+1) \\
=r-1r+2 t+1, \\
a_{r+2 t+2}=a_{r+2 t+1}-(r+2 t+1) \\
=2 r+t-(r+2 t+1) \\
=r-t-1r$, the even numbers all satisfy $a_{r}<r$, and there is one less even number than odd numbers. Therefore, the number of positive integers $r$ that satisfy $a_{r}<r \leqslant 3^{2017}$ is
$$
\frac{1}{2}\left(3^{2017}-2018-1\right)=\frac{3^{2017}-2019}{2} \text {. }
$$